IDEA使用JDBC連結MySql(java程式設計)
阿新 • • 發佈:2022-02-22
1、在Maven的pom.xml檔案中引入MySql的驅動
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency>
2、idea(版本:2021.2.2)JDBC連結MySql資料庫
package com.hong.test; import java.sql.*; public class TestJDBC { public static void main(String[] args) throws ClassNotFoundException, SQLException { String url = "jdbc:mysql://localhost:3306/JDBC?useUnicode=true&characterEncoding=utf-8"; String user = "root"; String password = "root"; //載入資料庫驅動 Class.forName("com.mysql.jdbc.Driver"); //建立資料庫連結物件 Connection connection = DriverManager.getConnection(url, user, password); //插入資料的sql語句 String sql = "insert into admin(username, password, email, birthday) VALUES (?,?,?,?)"; //操作資料庫 PreparedStatement PreparedStatement statement = connection.prepareStatement(sql); //插入資料 statement.setString(1,"李四"); statement.setString(2,"123456"); statement.setString(3,"[email protected]"); statement.setDate(4, new Date(new java.util.Date().getTime())); //i : 返回受影響的行數 int i = statement.executeUpdate(); if(i>0){ System.out.println("插入成功@"); }else{ System.err.println("插入失敗@"); } } }