在maven项目pom.xml中到入驱动包(以下是驱动包代码)
mysql
mysql-connector-java
8.0.15
导入成功会看到Maven Dependencies下有个mysql-connector-Java包
然后按下面步骤:
package com.base.day16;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//加载驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
//创建连接
//java10为数据库名
String url="jdbc:mysql://localhost:3306/java10?useSSL=false&serverTimezone=UTC";
String username="用户名";
String userpwd="密码";
Connection conn = DriverManager.getConnection(url,username,userpwd);
//创建Statement,执行sql
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select sname,sage,ssex from student1");
while(rs.next()){
System.out.println("名字"+rs.getString("sname"));
System.out.println("年齡"+rs.getInt("sage"));
System.out.println("性別"+rs.getString("ssex"));
}
//关闭连接
rs.close();
st.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}