// 首先要有 能操作mysql的.jar包才行,https://dev.mysql.com/downloads/connector/j/ 选择platform independent 然后下 //载4.4M的zip,解压拿到.jar 放到 ide的包里面去 import java.sql.*; public class mysql_connect { Connection con; public Connection getConnection(){ try { Class.forName("com.mysql.cj.jdbc.Driver"); //加载数据库驱动 }catch (ClassNotFoundException e){ e.printStackTrace(); } try{ con=DriverManager.getConnection("jdbc:mysql:"+"//127.0.0.1:3306/my_company_test","root","mysql"); System.out.println("连接成功"); //定义链接数据库方法 }catch (SQLException e){ e.printStackTrace(); } return con; } public static void Cha(){ mysql_connect c=new mysql_connect(); Connection con =c.getConnection(); //调用链接数据库 try{ Statement sql = con.createStatement(); // 定义sql语句 ResultSet res = sql.executeQuery("select * from test"); //获取查询的数据 res.last(); int n=res.getRow(); //通过指针获取返回数据长度 System.out.println(n); while (res.next()){ String name=res.getNString("name"); System.out.println(name); } }catch (Exception e){ e.printStackTrace(); } } private static void ZengShanGai() { mysql_connect c=new mysql_connect(); Connection con =c.getConnection(); //调用链接数据库 try{ System.out.println("执行增语句"); PreparedStatement sql=con.prepareStatement("insert into test (name) values (?)"); PreparedStatement sql2=con.prepareStatement("insert into test (name) values (?)"); sql.setString(1,"zhangsan2"); sql2.setString(1,"lisi"); sql.executeUpdate(); sql2.execute(); con.close(); // 断开连接 System.out.println("执行更改语句"); PreparedStatement sql22=con.prepareStatement("update test set name=? where name='zhangsan'"); sql22.setString(1,"zhangsan3"); sql22.executeUpdate(); System.out.println("执行删除语句"); PreparedStatement sql33=con.prepareStatement("delete from test where name=?"); sql33.setString(1,"zhangsan3"); sql33.executeUpdate(); con.close(); }catch (Exception e){ e.printStackTrace(); } } public static void main(String args[]){ // Cha(); ZengShanGai(); } }
Java实现数据库增删改查(新手篇)
最新推荐文章于 2024-06-29 16:15:57 发布