MySQL---JDBC简单sql命令-插入

MySQL---JDBC简单sql命令-插入_第1张图片

代码如下:

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class testjdbc {
    public static void main(String[] args) throws SQLException {
        Scanner sc=new Scanner(System.in);
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
        //让代码与数据库服务器建立连接
        Connection connection=dataSource.getConnection() ;
        //输入指定的数据
        System.out.println("请输入姓名");
        String name =sc.next();
        System.out.println("请输入学号");
        int id=sc.nextInt();
        String sql="insert into students values(?,?)";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        //进行替换操作
        preparedStatement.setString(1,name);
        preparedStatement.setInt(2,id);
        System.out.println("preparedStatement:"+preparedStatement);
        int ret =preparedStatement.executeUpdate();
        System.out.println(ret);
        preparedStatement.close();
        connection.close();

    }
}

你可能感兴趣的:(MySQL,intellij-idea,mysql)