JDBC连接MySQL程序

最近一直在学习hibernate,一回想起JDBC感觉陌生了好多,刚才编了个小程序复习一下,我这里把JDBC的连接写在一个类里,这样我们就可以只写一遍这些连接了,简化了代码也方便了调用。
package jdbctest;
import java.sql.*;
public class JDBCinit {
	
	public static Connection getConnection(){
		Connection conn = null ;
		try {
			//注册驱动
			Class.forName("com.mysql.jdbc.Driver");
			//获取连接,账号密码根据自己数据库进行填写
			conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?user=xxx&password=xxx");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}
		return conn;
	}
	
	//创建状态对象,以便发送SQL语句到数据库
	public static Statement getStatement(Connection conn){
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}
	//从数据库里进行查询操作
	public static ResultSet getResultSet(Statement stmt,String sql){
		ResultSet rs = null;
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	//关闭结果集
	public static void getClose(ResultSet rs){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	//关闭statement对象
	public static void getClose(Statement stmt){
		if (stmt != null) {
			try {
				stmt.close();
				stmt = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	//关闭数据库连接
	public static void getClose(Connection conn){
		if(conn != null){
			try {
				conn.close();
				conn = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

接着我们再写一个测试类,来验证下我们写的到底对不对

import java.sql.*;


public class TestJDBC {

	public static void main(String[] args) {
		Connection conn =JDBCinit.getConnection();
		Statement stmt = JDBCinit.getStatement(conn);
		//根据自己的数据库进行查询
		ResultSet rs = JDBCinit.getResultSet(stmt, "select * from xxx");
		try {
			while(rs.next() == true){
				//xxx为数据库字段名,更具实际情况填写
				System.out.println("password:"+rs.getString("xxx"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		JDBCinit.getClose(rs);
		JDBCinit.getClose(stmt);
		JDBCinit.getClose(conn);
	}

}
大功告成~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值