Java连接MySQL数据库
工具
- eclipse
- MySQL5.7
- MySQL连接驱动:mysql-connector-java-5.1.39-bin.jar
- 连接驱动链接: https://pan.baidu.com/s/1I54wRAEa6-gwz9TVSUQ0Zg
提取码:tt85
新建Java项目导入jar包
项目名称:Java_con
在工程根目录下新建文件夹,命名为“lib”
将下载好的jar包复制粘贴到lib文件夹中
点击——右键——Build Path——Add to Build Path——完成
下一步就是新建class文件,编写Java代码。部分代码已给出注释,童鞋们复制的时候记得修改类名!
代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Student_Test {
public static void main(String[] args) {
Connection con; //声明Connection对象
String driver = "com.mysql.jdbc.Driver"; //驱动程序名
String url = "jdbc:mysql://localhost:3306/aaaa?useSSL=false"; //URL指向要访问的数据库名aaaa
String user = "root"; //MySQL配置时的用户名
String mima = ""; //MySQL配置时的密码
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url,user,mima);
if(!con.isClosed())
System.out.println("成功连接数据库!");
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
//要执行的SQL语句
String sql = "select * from websites";
//3.ResultSet类,用来存放获取的结果集!!
ResultSet rs = statement.executeQuery(sql);
System.out.println("---------------------------");
System.out.println("执行结果如下所示:");
System.out.println("---------------------------");
System.out.println("网站名称" + "\t" +"网站地址"+"\t"+"Alexa排名"+"\t"+"国家");
System.out.println("---------------------------");
String name = null;
String urlname=null;
String alexa=null;
String country= null;
while(rs.next()){
//获取name这列数据
name = rs.getString("name");
//获取urlname这列数据
urlname=rs.getString("urlname");
//获取Alexa这列数据
alexa=rs.getString("alexa");
//获取country这列数据
country= rs.getString("country");
//输出结果
System.out.println(name + "\t" +urlname+"\t"+alexa+"\t"+country);
}
rs.close();
con.close();
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!!");
}
}
}
数据库
数据库名:aaa
表名:websites