当前位置:Gxlcms > 数据库问题 > 使用JDBC连接MySQL数据库

使用JDBC连接MySQL数据库

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

com.llt.demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class DBHelper { public static final String url = "jdbc:mysql://127.0.0.1/test"; // jdbc:mysql://host:port/database name public static final String name = "com.mysql.jdbc.Driver"; public static final String user = "root"; // 数据库登录用户 public static final String password = "123456"; public Connection connection = null; public PreparedStatement pst = null; // 数据库登录密码 public DBHelper(String sql) { try { Class.forName(name);// 指定连接类型 connection = DriverManager.getConnection(url, user, password);// 创建连接 pst = connection.prepareStatement(sql);// 执行Sql语句 } catch (Exception e) { e.printStackTrace(); } } public void close() { try { this.connection.close(); this.pst.close(); } catch (Exception e) { } } } View Code

 

然后创建一个简单的类,测试连接一下MySQL数据库 技术分享
package com.llt.demo;
 
import java.sql.ResultSet;
 
public class test {
 
       public static String sql = "";
       public static DBHelper db = null;
       public static ResultSet ret = null;
 
       public static void main(String[] args) {
             // TODO Auto-generated method stub
             String sql = "select * from book";
             db = new DBHelper(sql);
             try {
                    ret = db.pst.executeQuery();
                    while (ret.next()) {
                           int id = ret.getInt(1);
                           String name = ret.getString(2);
                           System.out.println("id:" + id + ",name:" + name);
 
                    }
                    // 使用完后将数据库连接关闭
                    ret.close();
                    db.close();
             } catch (Exception e) {
                    e.printStackTrace();
             }
       }
}
View Code

 

输出MySQL数据库book表中的内容: 技术分享

 

技术分享

使用JDBC连接MySQL数据库

标签:com   user   print   ima   rac   ring   sql   lips   pack   

人气教程排行