当前位置:Gxlcms > 数据库问题 > JAVA使用JDBC连接MySQL数据库 二(2)

JAVA使用JDBC连接MySQL数据库 二(2)

时间:2021-07-01 10:21:17 帮助过:18人阅读

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 Statement statement; public DBHelper(){ 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);//使用prepareStatement来执行SQL语句 statement = (Statement) conn.createStatement();//使用statement来执行SQL语句 } catch (Exception e) { e.printStackTrace(); } } public void close() { try { this.conn.close(); //this.pst.close(); this.statement.close(); } catch (Exception e) { e.printStackTrace(); } } }

 

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();// 返回结果集
            DBHelper db = new DBHelper();//创建DBHelper对象  
            ResultSet rs = (ResultSet) db.statement.executeQuery(sql);// 返回结果集
            
            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数据库 二(2)

标签:localhost   加载   static   tco   manager   resultset   mysql数据库   exe   class   

人气教程排行