我想在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
}
}
}
答案 0 :(得分:0)
format)
和values
将此行更改为
String sql = "INSERT INTO document (document_id, document_name, format)" +
"VALUES (?, ?, ?)";
到
String sql = "INSERT INTO document(document_id, document_name, format) " +
"VALUES (?, ?, ?)";
答案 1 :(得分:0)
尝试这样做:
preparedStatement.executeUpdate(sql);
您还应该指定数据库
String sql = "INSERT INTO database_name.document (document_id, document_name, format)" +"VALUES (?, ?, ?)";
答案 2 :(得分:0)
enter code here
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();}
答案 3 :(得分:-1)
注意preparedStatement.executeUpdate()返回true(记录在插入,更新或删除时成功)或false(不成功)。因此,我建议打印出结果,看它是否有效。
至于没有收到错误消息,您是否正在使用异常而不是打印错误?在catch块中,输入e.printStackTrace()以查看错误是什么。