JDBC连接数据库的完整实例
package com.sinovatech.util;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtils {
private static final String URL = "jdbc:mysql://localhost:3306/mysql";
private static final String USER = "root";
private static final String PASSWORD = "123456";
private static Statement stmt;
// private static PreparedStatement pstmt;
private static ResultSet stmtrs;
// private static ResultSet pstmtrs;
private static Connection connection;
public DBUtils() {
super();
}
private static Connection getConnection() {
try {
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void main(String args[]) {
try {
// 加载MySql的驱动类
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace();
}
connection = DBUtils.getConnection();
try {
// 这里的sql是静态sql如果只是执行一次用Statement会比较好
Statement stmt = connection.createStatement();
String sql = "SELECT * FROM USER";
ResultSet stmtrs = stmt.executeQuery(sql);
while (stmtrs.next()) {
System.out.println("你好");
}
// 如果是动态的sql如果SQL语句被多次执行选用PreparedStatement是最好的。
// PreparedStatement:
// 数据库会对sql语句进行预编译,下次执行相同的sql语句时,数据库端不会再进行预编译了,而直接用数据库的缓冲区,提高数据访问的效率
PreparedStatement pstmt = connection.prepareStatement(sql);
ResultSet pstmtrs = pstmt.executeQuery();
while (pstmtrs.next()) {
System.out.println("你好");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (stmtrs != null) {
try {
stmtrs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}