jdbc__Statement对象的初步学习

// 是java.sql.Statement接口:用于执行静态sql语句,并返回响应结果的对象
     //1. ResultSet executeQuery(String sql) 根据执行语句返回结果集,只能执行select语句。
     //2. int executeUpdate(String sql) 根据执行的DML(insert update delete)语句,返回受影响的行数
     //3. boolean execute(String sql) 此方法可以执行任意sql语句。返回boolean值,表示是否返回ResultSet结果集。仅当执行select
     //   语句,且又返回结果时才返回true,其他语句都返回false
  // insert into users values(4,'abc','123456');
  // update users set name='abcd',password='234567' where id=4;
  //  delete from users where id=4;
package cw_jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import org.junit.Test;
public class TestCRUD {
 @Test
 public void testInsert() throws Exception{
  //1.加载驱动
  Class.forName("com.mysql.jdbc.Driver");  //反射机制加载驱动类
 // 2.获取连接Connection
   //主机:端口号/数据库名
     //map集合
 Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/cw?user=root&password=root");
 // 3.得到执行sql语句的对象Statement
 Statement stmt = conn.createStatement();
 // 4.执行sql语句,并返回结果
 int i=stmt.executeUpdate("insert into users values(4,'abc','123456')");
 if(i>0){
  System.out.println("Success");
 }
 // 5.处理结果
 
 // 6.关闭资源
 stmt.close();
 conn.close();

 @Test
 public void testUpdate() throws Exception{
  //1.加载驱动
    Class.forName("com.mysql.jdbc.Driver");  //反射机制加载驱动类
   // 2.获取连接Connection
     //主机:端口号/数据库名
       //map集合
   Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/competition?user=root&password=123");
   // 3.得到执行sql语句的对象Statement
   Statement stmt = conn.createStatement();
   // 4.执行sql语句,并返回结果
   int i=stmt.executeUpdate("update users set name='abcd',password='234567' where id=4");
   if(i>0){
    System.out.println("Success");
   }
   // 5.处理结果
   
   // 6.关闭资源
   stmt.close();
   conn.close();
 }
 @Test
 public void testDelete() throws Exception{
  //1.加载驱动
    Class.forName("com.mysql.jdbc.Driver");  //反射机制加载驱动类
   // 2.获取连接Connection
     //主机:端口号/数据库名
       //map集合
   Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/competition?user=root&password=123");
   // 3.得到执行sql语句的对象Statement
   Statement stmt = conn.createStatement();
   // 4.执行sql语句,并返回结果
   int i=stmt.executeUpdate("delete from users where id=4");
   if(i>0){
    System.out.println("Success");
   }
   // 5.处理结果
   
   // 6.关闭资源
   stmt.close();
   conn.close();
 }
}

猜你喜欢

转载自blog.csdn.net/zoweiccc/article/details/80721054