db.properties
* jdbc.driver=com.mysql.jdbc.Driver
* jdbc.url=jdbc:mysql://localhost:3306/databaseName
* jdbc.user=root
* jdbc.password=root
连接数据库工具类(不带连接池)
package pack;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class JDBCUtil {
private static String driver;
private static String url;
private static String user;
private static String password;
static {
try {
Properties prop = new Properties();
FileReader fr = new FileReader("db.properties");
prop.load(fr);
driver = prop.getProperty("jdbc.driver");
url = prop.getProperty("jdbc.url");
user = prop.getProperty("jdbc.user");
password = prop.getProperty("jdbc.password");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConn() throws Exception {
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
}
db.properties
* jdbc.driverClassName=com.mysql.jdbc.Driver
* jdbc.url=jdbc:mysql://localhost:3306/databaseName
* jdbc.username=root
* jdbc.password=root
连接数据库工具类(带dbcp连接池)
package pack;
import java.io.FileReader;
import java.sql.Connection;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
public class JDBCUtil {
private static BasicDataSource dataSource = new BasicDataSource();
private static String driverClassName;
private static String url;
private static String username;
private static String password;
static {
try {
Properties prop = new Properties();
FileReader fr = new FileReader("db.properties");
prop.load(fr);
driverClassName = prop.getProperty("jdbc.driverClassName");
url = prop.getProperty("jdbc.url");
username = prop.getProperty("jdbc.username");
password = prop.getProperty("jdbc.password");
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConn() throws Exception {
return dataSource.getConnection();
}
}
Statement对象常用方法
* int executeUpdate(String sql); --执行insert update delete语句.
* ResultSet executeQuery(String sql); --执行select语句.
* boolean execute(String sql); --执行select返回true 执行其他的语句返回false.
ResultSet对象常用方法
* Object getObject(int col); 获得任意对象,参数col表示从左往右第几列(从1开始)
* Object getObject(String columnName); 获得任意对象,参数columnName表示列名
* String getString(int col); 获得字符串,参数col表示从左往右第几列(从1开始)
* String getString(String columnName); 获得字符串,参数columnName表示列名
* int getInt(int col); 获得整形,,参数col表示从左往右第几列(从1开始)
* double getDouble(int col); 获得双精度浮点型,参数col表示从左往右第几列(从1开始)
PrepareStatement对象常用方法
* 执行sql语句
* int executeUpdate(); --执行insert update delete语句.
* ResultSet executeQuery(); --执行select语句.
* boolean execute(); --执行select返回true 执行其他的语句返回false.
* 设置实际参数
* setXxxx(int , T) 通过setter方法将?占位符替换成实际参数
* 例如:setString() 实际参数类型为hi字符串。