/**
*
* 使用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();
}
}
}
}
*/