首页 > 数据库技术 > 详细

JAVA使用JDBC连接MySQL数据库 二

时间:2017-02-09 11:11:31      阅读:226      评论:0      收藏:0      [点我收藏+]

 

JAVA连接MySQL稍微繁琐,所以先写一个类用来打开或关闭数据库:

public class DBHelper {

    String driver = "com.mysql.jdbc.Driver";
    String url= "jdbc:mysql://localhost:3306/test";
    String user = "root";
    String password = "123456";
    
    public Connection conn;
    public PreparedStatement pst;
    
    public DBHelper(String sql){
        try {
            // 加载驱动程序
            Class.forName(driver);
            // 连续数据库
            conn = (Connection) DriverManager.getConnection(url, user, password);
            if(!conn.isClosed()){
                System.out.println("Succeeded connecting to the Database!");
            }   
            pst = (PreparedStatement) conn.prepareStatement(sql);//准备执行语句
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void close() {
        try {
            this.conn.close();
            this.pst.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

再写一个JDBCTest.java来执行相关查询操作

public class JDBCTest {

    public static void main(String[] args){
        String sql = "select * from employee";//SQL语句
        try{
            DBHelper db = new DBHelper(sql);//创建DBHelper对象  
            ResultSet rs = (ResultSet) db.pst.executeQuery();// 返回结果集
            
            System.out.println("-----------------");
            System.out.println("姓名" +"\t"+ "邮箱" +"\t"+ "日期");
            System.out.println("-----------------");
            
            while(rs.next()) {
                //获取结果集中的数据
                String uname = rs.getString("name");
                String uemail = rs.getString("email");
                String uhiredate = rs.getString("hiredate");
                // 输出结果
                System.out.println(uname +"\t"+ uemail +"\t"+ uhiredate);
            }
            rs.close();
            db.close();//关闭连接 
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }
}

 

JAVA使用JDBC连接MySQL数据库 二

原文:http://www.cnblogs.com/liushao/p/6380723.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!