最简单的JDBC封装
import java.sql.*;
public class DBUtil {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456");
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
try {
if(resultSet != null){
resultSet.close();
}
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
测试
import java.sql.Connection;
import java.sql.PreparedStatement;
public class JDBCDemoUseUtil {
public static void main(String[] args) throws Exception {
Connection connection = DBUtil.getConnection();
String sql="insert into user(userid,username,sex)values(5,'孙七','男')";
PreparedStatement statement = connection.prepareStatement(sql);
int result =statement.executeUpdate();
if(result != -1){
System.out.println("注册成功!");
}else{
System.out.println("注册失败!");
}
DBUtil.closeAll(connection,statement,null);
}
}