Test 1
首先去查看一下MySQL的版本:mysql -V(在cmd中)
记得要启动MySQL服务
在cmd中验证是否可以登录数据库成功:mysql -u root -p(然后输入密码:root)
Test 2
在IDEA创建项目
在SQLyog中创建数据库
下载驱动并且导入项目中
Test 3
增删改 和 查
增删改
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo1 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/day3_01?useSSL=false", "root", "root");
if(connection!=null){
System.out.println("连接成功!");
Statement statement = connection.createStatement();
String sql = "INSERT INTO bank VALUES(1,'王五',1200)"; // 插入数据
// String sql = "DELETE FROM bank WHERE id=1"; // 删除数据
// String sql = "UPDATE bank SET username='李四' WHERE id=2"; //修改数据
int result = statement.executeUpdate(sql);
if(result>0){
System.out.println("数据插入成功!");
}else{
System.out.println("数据插入失败!");
}
connection.close();
}else{
System.out.println("连接失败!");
}
}
}
查
import java.sql.*;
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/day3_01?useSSL=false", "root", "root");
if(connection!=null){
System.out.println("连接成功!");
Statement statement = connection.createStatement();
// Scanner scanner = new Scanner(System.in);
// System.out.println("请输入用户名:");
// String username = scanner.next();
// System.out.println("请输入密码:");
// String password = scanner.next();
// String sql = "SELECT COUNT(1) as num FROM bank WHERE username = '%s' and money = %s;";
// String sql1 = String.format(sql, username, password);
// ResultSet result = statement.executeQuery(sql1);
// result.next();
// if(result.getInt("num") == 1){
// System.out.println("登录成功!");
// }else {
// System.out.println("登录失败!");
// }
String sql = "SELECT * FROM bank";
//String sql = "SELECT * FROM bank WHERE username = '张三' and money = 3200";
ResultSet result = statement.executeQuery(sql);
while(result.next()){
System.out.println(result.getString("username")+" "+result.getString("money"));
}
connection.close();
}else{
System.out.println("连接失败!");
}
}
}