JDBC连接MySQL程序

来源:互联网 发布:阿里云ecs搭建网站 编辑:程序博客网 时间:2024/06/05 23:58
最近一直在学习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);}}
大功告成~~~

0 0
原创粉丝点击