快速入门:
* 步骤:1. 导入驱动jar包 mysql-connector-java-8.0.17.jar1.复制mysql-connector-java-8.0.17.jar到项目的libs目录下2.右键-->Add As Library2. 注册驱动3. 获取数据库连接对象 Connection4. 定义sql5. 获取执行sql语句的对象 Statement6. 执行sql,接受返回结果7. 处理结果8. 释放资源
代码如下:
(代码有一点缺陷,后面有时间完善一下)
package jdbcDemo01;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;public class jdbcDemo {public static void main(String[] args) throws ClassNotFoundException, SQLException {String driver = "com.mysql.cj.jdbc.Driver";//驱动程序String url = "jdbc:mysql://localhost:3306/db3?serverTimezone=UTC";//数据库连接URL(“data”为数据库名)String username = "root";//账号String password = "root";//密码//1.导入驱动jar包//2.注册驱动Class.forName(driver);//3.获取数据库连接对象Connection conn = DriverManager.getConnection(url, username,password);//4.定义sql语句String sql = "update account set balance = 500 where id = 1";//5.获取执行sql的对象 StatementStatement stmt = conn.createStatement();//6.执行sqlint cnt = stmt.executeUpdate(sql);//7.处理结果System.out.println(cnt);//8.释放资源stmt.close();conn.close();}
}
如果程序无法运行,点击下面链接可能可以解决问题:
IDEA导入MySQL的jdbc驱动出现“java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver”