深圳精品网站建设,中国十大文旅策划公司,专业app开发公司,搜狗指数jdbc建立java和sql的连接
一.导包
1.首先新建一个项目
2.再新建一个包lib
3.把下好的sql包粘贴到lib里
4.右键lib包点击add as library
结束
二.注册驱动#xff1a;
DriverManager.registerDriver(new Driver());三.建立与数据库的连接#xff1a; String url…jdbc建立java和sql的连接
一.导包
1.首先新建一个项目
2.再新建一个包lib
3.把下好的sql包粘贴到lib里
4.右键lib包点击add as library
结束
二.注册驱动
DriverManager.registerDriver(new Driver());三.建立与数据库的连接 String urljdbc:mysql://127.0.0.1sql端口号/schooldb?serverTimezoneAsia/Shanghai;String userroot; //账户String passwordroot; //密码Connection connectionDriverManager.getConnection(url,user,password);四.发送sql Statement statementconnection.createStatement();statement.executeUpdate(insert into major(name)value(数学));五.关闭与数据库的连接
statement.close();
connection.close();插入方法eg
public static void main(String[] args) throws SQLException {SqlOperate.insert(lzy,男,1979-4-21,13152113467,1.88);}public static void insert(String name,String gender, String birthday,String phone,double height) throws SQLException {//注册驱动DriverManager.registerDriver(new Driver());String urljdbc:mysql://127.0.0.1:3306/schooldb?serverTimezoneAsia/Shanghai;String userroot;String passwordroot;//建立与数据库的连接Connection connectionDriverManager.getConnection(url,user,password);//发送sqlStatement statementconnection.createStatement();statement.executeUpdate(update student set namename,gendergender,birthdaybirthday,phonephone,heightheight);//关闭与数据库的连接statement.close();connection.close();}PreparedStatement实现发送sql
PreparedStatement psconnection.prepareStatement(insert into major(name)value(?)); //是占位符表示要插入一个参数ps.setObject(1,智能); //1表示在第一个?位置插入数据ps.executeUpdate();PreparedStatement psconnection.prepareStatement(update student set name?,gender?,birthday?,phone?,height? where number?);ps.setObject(1,name);ps.setObject(2,gender);ps.setObject(3,birthday);ps.setObject(4,phone);ps.setObject(5,height);ps.setObject(6,number);ps.executeUpdate();PreparedStatement和Statement本质区别PS的?占位符可以在参数进来时进行验证防止sql注入攻击更安全