package com.example.de1; import org.junit.Test; import java.sql.*; public class jdbc { private static final String url = "jdbc:mysql://127.0.0.1:3307/test";//默认127.0.0.1:3306,可省,jdbc:mysql:///test private static final String user ="root"; private static final String password ="123"; @Test public void f01() throws SQLException{ Connection conn = DriverManager.getConnection(url,user,password);//java公司提供的驱动管理类来获得连接,兼容coonection标准。 System.out.println(conn); } @Test public void f1() throws SQLException { Connection conn = DriverManager. getConnection(url, user, password); Statement stmt = conn. createStatement();// 执行对象(增删查改) //增 int line = stmt.executeUpdate( "insert into dept values(50, ' 开发部','南昌')"); System.out.println(line==1 ? "成功":"失败"); } //增 @Test public void f2() throws SQLException { Connection conn = DriverManager. getConnection(url, user, password); Statement stmt = conn. createStatement(); int line = stmt.executeUpdate( "insert into dept values(60, ' CAIWU','BEIJING')"); System.out.println(line==1 ? "成功":"失败"); } //删 @Test public void f3() throws SQLException { Connection conn = DriverManager. getConnection(url, user, password); Statement stmt = conn. createStatement(); int line = stmt.executeUpdate( "delete from dept where deptno = 50"); System.out.println(line==1 ? "成功":"失败"); } //改 @Test public void f4() throws SQLException { Connection conn = DriverManager. getConnection(url, user, password); Statement stmt = conn. createStatement(); int line = stmt.executeUpdate( "update dept set loc='SHANGHAI' where deptno = 60"); System.out.println(line==1 ? "成功":"失败"); } //查 @Test public void f03() throws SQLException{ Connection conn = DriverManager.getConnection(url,user,password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from dept where deptno = 10"); while(rs.next()){ int id = rs.getInt(1); /* String dname = rs.getString("dname"); String loc = rs.getString("loc");*/ Object ob1 =rs.getObject(2);// 利用多态 父类得到子类 Object ob2 =rs.getObject(3); System.out.println(id +" " + ob1 + " " +ob2); // System.out.println(id +" " + dname + " " +loc); } } }
新建lib包,把mysql驱动jar包复制到lib下,右击lib选择Add as Library
标签:JDBC,改查,stmt,Test,增删,println,line,password,conn From: https://www.cnblogs.com/oyww-2027/p/17595632.html