方法1.导入mysql-connector-java-8.0.16文件
方法2:运用maven来解决
加入:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
package jdbc;
import com.mysql.cj.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Dom1 {
public static void main(String[] args) throws SQLException {
//注册驱动
DriverManager.registerDriver(new Driver());
//建立与数据库连接
String url="jdbc:mysql://127.0.0.1:3306/student?serverTimezone=Asia/Shanghai";
String user="root";
String password="root";
Connection connection=DriverManager.getConnection(url,user,password);//ConnectionImpl@25359ed8
//System.out.println(connection);
//关闭与数据库的连接
statement.close();
connection.close();
}
}
package jdbc;
import com.mysql.cj.jdbc.Driver;
import java.sql.*;
public class Dom6 {
public static void main(String[] args) throws SQLException {
int a=f(2);
System.out.println(a);
}
public static int f (int num) throws SQLException {
//注册驱动
DriverManager.registerDriver(new Driver());
//建立与数据库连接
String url = "jdbc:mysql://127.0.0.1:3306/student?serverTimezone=Asia/Shanghai";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);//ConnectionImpl@25359ed8
PreparedStatement preparedStatement = connection.prepareStatement("select count(*)c from student where num=?");
preparedStatement.setObject(1,num);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt("c");
}
return 0;
}
}
DriverManager.registerDriver(new Driver());
//建立与数据库连接
String url="jdbc:mysql://127.0.0.1:3306/student?serverTimezone=Asia/Shanghai";
String user="root";
String password="root";
Connection connection=DriverManager.getConnection(url,user,password);//ConnectionImpl@25359ed8
//System.out.println(connection);
//发送sql
Statement statement =connection.createStatement();//StatementImpl@442675e1
//System.out.println(statement);
statement.executeLargeUpdate("insert into major(name)value('英语')");
//关闭与数据库的连接
statement.close();
connection.close();
package jdbc;
import com.mysql.cj.jdbc.Driver;
import java.sql.*;
public class Dom6 {
public static void main(String[] args) throws SQLException {
int a=f(2);
System.out.println(a);
}
public static int f (int num) throws SQLException {
//注册驱动
DriverManager.registerDriver(new Driver());
//建立与数据库连接
String url = "jdbc:mysql://127.0.0.1:3306/student?serverTimezone=Asia/Shanghai";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);//ConnectionImpl@25359ed8
PreparedStatement preparedStatement = connection.prepareStatement("select count(*)c from student where num=?");
preparedStatement.setObject(1,num);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt("c");
}
return 0;
}
}