1、在src目录下建立jdbc.propertise文件 user=root//数据库登录账户 password=123456//数据库登录密码 url=jdbc:mysql://localhost:3306/shujukumingzi//这里是url,如果要实现其他指定操作在后面加相应的参数 driverClass=com.mysql.jdbc.Driver//driver驱动
2、对建立数据库连接和关闭操作进行封装,以便之后的一系列操作的调用,这里利用反射技术来建立连接。
public class JDBCUtilse {
public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
InputStream is = Jdbc_Test5.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClass");
Class.forName(driverClass);
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
public static void close(Connection conn, Statement statement) throws SQLException {
if(conn != null)
{
conn.close();
}
if (statement != null)
{
statement.close();
}
}
}
3、实现通用的select操作
class PreparedStatement_Test3 {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
String sql = "select * from user where id < ?";
query(sql,3);
}
public static void query(String sql,Object...args) throws SQLException, IOException, ClassNotFoundException {
Connection conn = JDBCUtilse.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i ++)
{
ps.setObject(i + 1,args[i]);
}
ResultSet rs = ps.executeQuery();
ResultSetmetaData rsmd = rs.getmetaData();
int columnCount = rsmd.getColumnCount();
while (rs.next())
{
for (int i = 0; i < columnCount;i++ )
{
System.out.print(rs.getObject(i + 1 ) + " ");
}
System.out.println();
}
rs.close();
JDBCUtilse.close(conn,ps);
}
}
4、实现通用insert,delect,update操作
class PreparedStatement_Test2 {
public static void main(String[] args) throws Exception {
String sql="delect from user where id=? or id=?";
update(sql,1,2);
}
public static void update(String sql,Object...args) throws SQLException, IOException, ClassNotFoundException {
Connection conn=JDBCUtilse.getConnection();
PreparedStatement ps=conn.prepareStatement(sql);
for (int i=0;i<=args.length;i++){
ps.setObject(i,args[i]);
}
ps.executeUpdate();
JDBCUtilse.close(conn,ps);
}
}
总结:一系列的操作都是建立连接,再关闭,采用数据连接池会更加方便,三种连接池均可。



