Java Netbeans MySql数据库连接

evrscar2  于 2022-11-10  发布在  Java
关注(0)|答案(4)|浏览(167)

我想用Java Netbeans中的Mysql连接的正常程序将行插入MySql数据库,但当我运行此代码时,我的数据库不受影响。我已经设置了与Netbeans和Mysql的连接,它工作正常。
编码:

import java.sql.*;

    public class MySqlConnection {

       static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
       static final String DB_URL = "jdbc:mysql://localhost:3306/migration";
       static final String USER = "root";
       static final String PASS = "ngts12345";

       public static void main(String[] args) {

            Connection conn = null;

            try{
             Class.forName("com.mysql.jdbc.Driver");
             System.out.println("Connecting to a selected database...");
             conn = DriverManager.getConnection(DB_URL, USER, PASS);
             System.out.println("Connected database successfully...");
             System.out.println("Inserting records into the table...");

             String sql = "INSERT INTO document (document_id, document_name, format)" +
            "VALUES (?, ?, ?)";
             PreparedStatement preparedStatement = conn.prepareStatement(sql);
             preparedStatement.setInt(1, 1);
             preparedStatement.setString(2, "Test2");
             preparedStatement.setString(3, "Test3");
             preparedStatement.executeUpdate(); 
             preparedStatement.close();  
             conn.close();  
        }catch(SQLException se){
          //Handle errors for JDBC

       }catch(Exception e){
          //Handle errors for Class.forName

       }
     }
  }
ltqd579y

ltqd579y1#

format)values后面没有空格
将此行更改为

String sql = "INSERT INTO document (document_id, document_name, format)" +
        "VALUES (?, ?, ?)";

String sql = "INSERT INTO document(document_id, document_name, format) " +
        "VALUES (?, ?, ?)";
agxfikkp

agxfikkp2#

请尝试执行以下操作:

preparedStatement.executeUpdate(sql);

还应指定数据库

String sql = "INSERT INTO database_name.document (document_id, document_name, format)" +"VALUES (?, ?, ?)";
u1ehiz5o

u1ehiz5o3#

try{      
  Class.forName("com.mysql.jdbc.Driver"); // MySQL database  connection
  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306","root","");
  String sql = "select * from 'table_name'.database_name where user=? and pass=?";
  pst = conn.prepareStatement(sql);
  rs= pst.executeQuery();
}
neskvpey

neskvpey4#

注意preparedStatement.executeUpdate()返回true(记录成功插入、更新或删除)或false(不成功)。因此,我建议打印出结果,看看它是否有效。
至于没有得到错误消息,您是在使用异常而不输出错误吗?在您的catch块中,放入e.printStackTrace()以查看错误是什么。

相关问题