如下JDBC方式连接数据库的代码
package com.company;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
public class Conn {
// 申明Connection对象
Connection con;
/*连接mySql*/
public Connection getmySqlConnection(){
try {
//加载数据库驱动类
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库驱动加载成功!");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
// 通过访问数据库的URL获取数据库连接对象
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDataBase","root","pwd");
System.out.println("数据库连接成功,哈哈!!");
}
catch (SQLException e){
e.printStackTrace();
}
// 返回一个Connection对象
return con;
}
public static void main(String args[]){
Conn c = new Conn();
// 调用连接数据库方法
c.getmySqlConnection();
}
}
运用报错
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
原因就是没有导入mysql-connector jar包
首先下载mysql-connector jar包
https://dev.mysql.com/downloads/file/?id=480090
解压mysql-connector-java-5.1.47
1.Idea->File->Project Structure
2.选择Libraries
3.点击+号->选择Java
4.选择刚才下载解压好的jar包
这样连接数据就成功了。运用输出
数据库驱动加载成功!
Mon Dec 03 15:48:56 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
数据库连接成功,哈哈!!
有个WARN警告,修改一下连接方式
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDataBase?useSSL=false","root","pwd");
运行后就没有警告信息了
说明
1.通过java.lang包的静态方法forName()来加载JDBC驱动程序,如果加载失败会抛出ClassNotFoundException异常。
2.通过java.sql包中类DriverManager的静态方法getConnection(String url,String user, String passwird)建立数据库连接。该方法3个参数依次指定预连接数据库的路径、用户名、密码。返回Connection对象。如果连接失败,则抛出SQLException异常。
数据库连接成功后,我们就可以访问了
新建一个Gradation类、注释Conn类的Main方法
package com.company;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Gradation {
// 申明Connection对象
static Connection con;
// 申明Statement对象
static Statement sql;
// 申明ResultSet对象
static ResultSet res;
public static void main(String args[]){
// 创建对象
Gradation c = new Gradation();
// 与数据连接
con = new Conn().getmySqlConnection();
try {
// 实例化Statement
sql = con.createStatement();
// 执行sql语句,返回结果集
res = sql.executeQuery("select * from tb_user");
// 如果当前语句不是最后一条,则进入循环
while (res.next()){
String name = res.getString("user_name");
String age = res.getString("user_age");
System.out.println("姓名:"+name+" 年龄:"+age);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}