通过JDBC连接数据库(二)
程序员文章站
2022-05-18 19:36:40
...
这次是建一个JDBCUtil类,代码如下:
package com.huawei;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author zhangzhao
*
* 2012-2-17下午08:53:27
*/
public final class JDBCUtil {
private static String url="jdbc:mysql://localhost:3306/jdbc";
private static String user="root";
private static String password="root";
private JDBCUtil()
{
}
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, user, password);
}
public static void free(ResultSet rs,PreparedStatement pStatement,Connection conn){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if(pStatement!=null)
pStatement.close();
} catch (Exception e2) {
// TODO: handle exception
}
finally{
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
主函数如下:
package com.huawei;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author zhangzhao
*
* 2012-2-17下午08:39:25
*/
public class JDBCTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
template();
}
public static void template()
{
Connection conn=null;
PreparedStatement pStatment=null;
ResultSet rs=null;
try {
conn=JDBCUtil.getConnection();
pStatment=conn.prepareStatement("select * from user");
rs=pStatment.executeQuery();
while(rs.next()){
System.out.println(rs.getObject(1)+"\t"+rs.getObject(2)+"\t"+rs.getObject(3)+"\t"+rs.getObject(4));
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
//释放
JDBCUtil.free(rs, pStatment, conn);
}
}
}
上一篇: pandas常用的方法
下一篇: 二叉树下