一:引入mysql驱动:mysql-connector-java-5.0.8-bin.jar
二:在src下新增conf.properties配置文件,用于配置数据库的配置信息
driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/jmt2017 username=root password=root
三:新增JDBCUtils用于获取连接,关闭连接
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
private JDBCUtils(){}
private static void setProperties(){
try {
Properties properties = new Properties();
properties.load(new FileReader("src/conf.properties"));
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
static {
setProperties();
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void closeResource(ResultSet rs, PreparedStatement ps,Connection conn){
try {
if(rs != null){
rs.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(ps != null){
ps.close();
ps = null;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(conn != null){
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static void closeResource(Statement ps,Connection conn){
try {
if(ps != null){
ps.close();
ps = null;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(conn != null){
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
四:执行sql语句,操作数据库:
①获取数据库连接Connection
Connection conn = JDBCUtils.getConnection();
②根据连接获取PreparedStatement执行对象
PreparedStatement ps = conn.prepareStatement("delete from users where id = ?");
③执行sql得到结果集
ResultSet resultSet = ps.executeQuery();
④解析结果
while (resultSet.next()){
resultSet.getString("id");}
⑤关闭连接
JDBCUtils.closeResource(resultSet,ps,conn);
Connection conn = null; PreparedStatement ps = null; ResultSet resultSet = null; try { conn = JDBCUtils.getConnection(); ps = conn.prepareStatement("select * from users"); resultSet = ps.executeQuery(); while (resultSet.next()){ String id = resultSet.getString("id"); String name = resultSet.getString("name"); String password = resultSet.getString("password"); System.out.println(id+"..."+name+"...."+password); } } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtils.closeResource(resultSet,ps,conn); }