您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
04-JDBC-API详解-Statement(单元测试与执行语句的影响行数在DDL与DML下的异同)
发布时间:2024-11-13 15:42:33编辑:雪饮阅读()
-
executeUpdate的执行结果不总是操作成功就能是大于0.比如DDL的drop语句即便成功,也返回0.所以不可轻易用此结果判断操作是否成功,视情况而定,而我则只按是否抛出异常来决定。
用几个单元测试试试。
package com;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class demo2 {
@Test
public void testDML() throws Exception {
String url="jdbc:mysql://192.168.217.132/demo?useSSL=false";
String username="demo";
String password="xy220807";
Connection conn= DriverManager.getConnection(url,username,password);
Statement stmt=conn.createStatement();
String sql="update account set money=22 where id = 1";
int count=stmt.executeUpdate(sql);
System.out.println("操作1=》影响行数:"+count);
String sql2="update account set money=22 where id = 22";
int count2=stmt.executeUpdate(sql2);
System.out.println("操作2=》影响行数:"+count2);
stmt.close();
conn.close();
}
@Test
public void testDDL() throws Exception {
String url="jdbc:mysql://192.168.217.132/demo?useSSL=false";
String username="root";
String password="1448169a3cb137d7";
Connection conn= DriverManager.getConnection(url,username,password);
Statement stmt=conn.createStatement();
String sql3="create database db2 ";
int count3=stmt.executeUpdate(sql3);
System.out.println("操作3=》影响行数:"+count3);
String sql4="drop database db2 ";
int count4=stmt.executeUpdate(sql4);
System.out.println("操作4=》影响行数:"+count4);
}
}
这里还有用到root账号,root账号也是要先开启远程访问,因为我的mysql主机相对来说是非本地的。新版宝塔好像只要放行3306端口,mysql的root就已经支持远程访问了,不太清楚了。但好像昨晚我也执行过让root远程访问的语句。
关键字词:jdbc,ddl,dml,单元测试