Java-mysql的jdbc数据库连接
1.注:(这里使用jetbrains)
1)项目使用JAVA-SDK8
2)由于数据库是mysql8的,所以引用的jar包需要升级
2.操作
1)新建一个lib文件夹,将jdbc的jar包放入,之后记得右击lib文件夹进行应用【Add as Library...】(eclipse应用请百度)
2)代码
package com.company; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Main { public static void main(String[] args) throws Exception { // write your code here //导入驱动jar包 Class.forName("com.mysql.cj.jdbc.Driver"); //获取数据连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Offical?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","root"); //定义sql语句 String sql = "select * from user"; //获取执行sql的对象 Statement smt = conn.createStatement(); //执行 ResultSet result = smt.executeQuery(sql); while(result.next()){ String name = result.getString("UserName"); System.out.println(name); }
result.close(); smt.close(); conn.close(); } }
注:这里在mysql5之后的jar包可以省略驱动注册(Class.forName),包里默认有
3.结果
参阅:https://www.bilibili.com/video/BV1vk4y117fU?p=497
https://www.runoob.com/java/java-mysql-connect.html