JDBC使用Statement执行DML语句(附加工具类)

package Demo;
/**
 * 
 * 使用Statement执行DML语句
 *
 */


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


import org.junit.Test;




public class Demo2{
private String url = "jdbc:mysql://localhost:3306/day16";
private String user = "root";
private String password = "root";

@Test
public void testInsert(){
Connection connection = null;
Statement statement = null;
try {
//1.注册驱动
/*Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
connection = DriverManager.getConnection(url, user, password);*/
connection = JdbcUtil.getConnection();
//3.创建Statement对象
statement = connection.createStatement();
//4.sql语句
String sql = "INSERT student(NAME, sex)VALUES('张三','男');";
//5.执行sql
int count = statement.executeUpdate(sql);
System.out.println("影响了"+count+"行");
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException();
}finally{
JdbcUtil.close(connection, statement);
/*if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException();
}
}*/
}

}

}


/**

package Demo;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


public class JdbcUtil {
   
private static String url = "jdbc:mysql://localhost:3306/day16";
private static String user = "root";
private static String password = "root";

static{
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println("出错");
}
}
public static Connection getConnection(){
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
return connection;
}
public static void close(Connection connection,Statement statement){
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException();
}
}
}
}



*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值