当前位置:Gxlcms > 数据库问题 > java(eclipse)和数据库(mysql)的连接

java(eclipse)和数据库(mysql)的连接

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

void getConnection() { Connection con = null; Statement stmt = null; ResultSet rs = null; try { // 获取数据库驱动名称(mysql数据库) Class.forName("com.mysql.jdbc.Driver"); // 进行数据库连接,dvd是数据库名称,root是数据名,123456是数据密码 con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/dvd", "root", "123456"); // 执行mysql语句 String sql = "select * from dvd1"; //实例化预处理Statement对象 stmt = con.createStatement(); //执行mysql代码 rs = stmt.executeQuery(sql); // 处理得到的数据 while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String state = rs.getString("state"); String date = rs.getString("date1"); int count = rs.getInt("count1"); System.out.println(id + "\t" + name + "\t" + state + "\t" + date + "\t" + count); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally {// 保证 在数据库和eclipse之间关闭 // 关闭数据库 try { rs.close(); stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

这是在学习中的基本操作,可以把上面的mysql执行提出来,把eclipse和数据放在一个方法中,下次使用的时候就直接调用

public Connection getConnection(){
        try {

            // 装载JDBC驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            // 连接数据库
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/zxd_0922", "root", "123456"); // 创建语句对象
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

每次调用时,需要接受con数据,

con=m.getConnection();

这是mysql和eclipse连接,第一次写博客,希望大家多多支持,有错误指出,对你有帮助点个赞。

java(eclipse)和数据库(mysql)的连接

标签:

人气教程排行