//分享的连接所需的jar包链接:https://pan.baidu.com/s/1rq3IrqJR6lzw6EJIzopDaw 密码:nnsj
数据库的连接步骤如下:
前提:数据库连接好了并且运行无误,有一个数据库db_test中建立了一个表如tb_test
主要方法:
注意改一下包名、数据库名、表名
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import com.mysql.jdbc.Statement;
public class TestOne {
public static void main(String[] args) {
String dbClassName = "com.mysql.jdbc.Driver";// MySQL数据库驱动类的名称
String tbName = "chatuser";
String dbUser = "root";// 访问MySQL数据库的用户名
String dbPwd = "root";// 访问MySQL数据库的密码
String dbName = "webchat";// 访问MySQL数据库中的实例
String dbUrl = "jdbc:mysql://127.0.0.1:3306/"+dbName+"?useUnicode=true&characterEncoding=utf-8&useSSL=false";// 访问MySQL数据库的路径
Connection conn = null;// MySQL数据库的连接对象
java.sql.Statement stmt = null;
ResultSet rs = null;
try {
if (conn == null) {
Class.forName(dbClassName).newInstance();// 实例化MySQL数据库的驱动
conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);// 连接MySQL数据库
stmt = conn.createStatement();
System.out.println("连接数据库成功!");
//查询
String sql = "SELECT * FROM "+tbName;//注意from后边有一个空格
//rs = stmt.executeQuery("SELECT * FROM webchat.chatuser");
rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.print(rs.getInt(1)+" ");
System.out.println(rs.getString(2));
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "请将MySQL的JDBC驱动包复制到lib文件夹中。");// 捕获异常后,弹出提示框
System.exit(-1);// 系统停止运行
} catch (Exception e) {
e.printStackTrace();
}
}
}