一、在项目中导入驱动包
**1、在mysql数据库默认安装位置(我的是C:\Program Files (x86)\MySQL\Connector J 8.0)复制
mysql-connector-java-8.0.11.jar;将其放到项目目录下,
2、在IDEA:file->Project Structure->Moudles->dependencies中添加选项卡中选择jars;
二、通过JDBC操作mysql数据库
实现代码如下:
import java.sql.*;
public class java_jdbc {
private static final String url="jdbc:mysql://localhost:3306/db_infomanager?useSSL=false&characterEncoding=utf-8&serverTimezone=Hongkong";
private static final String UserNmae="root";
private static final String pwd="0000";
public static void update(){
Connection connection=null;
Statement stmt=null;
ResultSet rst=null;
try {
//a.import the driver package and load the specific driver Class
Class.forName("com.mysql.cj.jdbc.Driver"); //load the specific driver class;
//b.Establish a connection to the database;
connection = DriverManager.getConnection(url,UserNmae,pwd);
//c.send sql,execute;
stmt=connection.createStatement();
// String sql="insert into tb_student values('2015310012',"+"'沈天华'"+","+"'男'"+",25,"+"'黑龙江'"+",'汉','AC1302')";
//String sql="delete from tb_student where studentNo="+"'2015310012'"+";
String sql="select * from tb_student";
//d.execute sql;
// int count=stmt.executeUpdate(sql);//can only be use for: insert,delete,update;
//f.resultset ;if the way you do it is select,you should use this method: stmt.executeQuery(sql);
rst=stmt.executeQuery(sql);
//e.result of handing;
while(rst.next()){
String name= rst.getString("studentName");
int age=rst.getInt("age");
System.out.println(name+"----"+age);
}
/* if(count>0){
System.out.println("successful!");
}else {
System.out.println("defeat!");
}*/
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();;
}
finally {
try {
if(rst!=null)
rst.close();
if (stmt!=null)
stmt.close();
if(connection!=null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
update();
}
}