代码1
import com.mysql.jdbc.Driver; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class Demo7 { @Test public void test1() throws SQLException { //注册驱动 DriverManager.registerDriver(new Driver()); //建立连接 String url="jdbc:mysql://192.168.177.151:4000/test"; //用户名 String user="root"; //密码 String pwd="123456"; //获取连接 Connection connection=DriverManager.getConnection(url,user,pwd); //创建命令发送器 Statement statement=connection.createStatement(); //准备sql String sql="insert into user values(null,'李白','123')"; //执行sql,获取结果 int i = statement.executeUpdate(sql);//输出1 //输出结果 System.out.println(i); //关闭资源 statement.close(); connection.close(); } @Test public void test2() throws ClassNotFoundException, SQLException { //注册驱动 Class.forName("com.mysql.jdbc.Driver"); //获取连接 String url="jdbc:mysql://192.168.177.151:4000/test"; String user="root"; String passwd="123456"; Connection connection=DriverManager.getConnection(url,user,passwd); //创建命令发送器 Statement statement=connection.createStatement(); //准备sql String sql="update user set passwd='456' where id=1"; //发送sql,获取结果 int i = statement.executeUpdate(sql); System.out.println(i>0?"成功":"失败"); //关闭资源 statement.close(); connection.close(); } }
代码2