在Java项目中如何更新MySQL数据库

2024年06月01日 建站教程

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
 
public class InsertData {
   
  public static void main(String[] args) {
    String url = "jdbc:mysql://localhost:3306/mydatabase";
    String username = "root";
    String password = "password";
     
    try {
      Connection connection = DriverManager.getConnection(url, username, password);
      Statement statement = connection.createStatement();
       
      String insertQuery = "INSERT INTO mytable (column1, column2) VALUES ('value1', 'value2')";
      int rowsAffected = statement.executeUpdate(insertQuery);
       
      System.out.println("Rows affected: " + rowsAffected);
       
      statement.close();
      connection.close();
    } catch (SQLException e) {
      System.out.println("插入失败原因: " + e.getMessage());
    }
  }
}

本文链接:http://so.lmcjl.com/news/5747/

展开阅读全文
相关内容