创建 JDBCUtils 类
package Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String user;
private static String password;
private static String url;
private static String driver;
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driver = properties.getProperty("driver");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection(){
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static void close(ResultSet rs, Statement st, Connection conn){
try{
if(rs != null){
rs.close();
}
if(st != null){
st.close();
}
if(conn != null){
conn.close();
}
}catch (SQLException e){
throw new RuntimeException(e);
}
}
}
DML 语句测试
package Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Test11 {
public static void main(String[] args){
Connection conn = null;
String sql = "update `admin` set password = ? where name = ?";
PreparedStatement ps = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, "356");
ps.setString(2, "Sherry");
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.close(null, ps, conn);
}
}
}
DQL 语句测试
package Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test12 {
public static void main(String[] args) {
Connection conn = null;
String sql = "select `name`, password from admin";
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
String name = rs.getString(1);
String password = rs.getString(2);
System.out.println(name + "\t" + password);
}
}catch(SQLException e){
e.printStackTrace();
}finally {
JDBCUtils.close(rs, ps, conn);
}
}
}