嘗試在Java中將單個行插入到數據庫中。它只插入第一列,我不知道爲什麼。這裏是代碼:Java sql插入JOptionpane
@Override
public void actionPerformed(ActionEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
int x = 1;
int limit;
//promts the user to enter input
// String InputString = JOptionPane.showInputDialog(null, "Enter the Number of Countries: ",JOptionPane.QUESTION_MESSAGE);
// limit = Integer.parseInt(InputString);
Connection connection;
PreparedStatement ps;
try {
String dbName = "osdesign";
String dbUserName = "root";
String dbPassword = "";
//String u = jtfuser.getText();
//String p =jpfpass.getName();
String connectionString = "jdbc:mysql://localhost/" + dbName + "?user="
+ dbUserName + "&password=" + dbPassword
+ "&useUnicode=true&characterEncoding=UTF-8";
connection = DriverManager.getConnection(connectionString);
JOptionPane.showMessageDialog(null, "Connected!");
//int x = 1;
User List = new User();
//User[] List = new User [limit];
//String query;
//for (x = 0; x < limit; x++)
// {
///List[x] = new User();
//List[x].User_type = null;
List.input(x);
//String sql = "INSERT into `userlist` (`UsrCode`, `UsrName`, `UsrPass`, `UsrPassChgDays`, `UsrPassChgDate`, `Usrtype`) VALUES(?, ?, ?, ?, ?, ?);";
PreparedStatement preparedStmt = connection.prepareStatement("INSERT INTO `userlist`" +
"VALUES(?, ?, ?, ?, ?, ?);");
String ID = List.ID;
String name = List.name;
preparedStmt.setString(1, ID);
preparedStmt.setString(2, name);
preparedStmt.setString(3, List.password);
preparedStmt.setString(4, List.Usr_PassChgDays);
preparedStmt.setString(5, List.data_of_passChg);
preparedStmt.setString(6, List.User_type);
preparedStmt.executeUpdate();
//btnlogin.equals(result);
// panel.add(btnlogin);
// panel.add(jpfpass.getName(),btnlogin);
if (preparedStmt.equals(true)) {
JOptionPane.showMessageDialog(null, "Great sucess!!!");
//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} else {
JOptionPane.showMessageDialog(null, "FUCK!!!");
}
//JOptionPane.showMessageDialog(null, "User sucessfully created");
} catch (SQLException ex) {
Logger.getLogger(RychlikSystemversion0.class.getName()).log(Level.SEVERE, null, ex);
}
}
在互聯網上看到無處不在,並嘗試每一個伎倆,我老實說,困惑。有人能幫助我嗎?
您必須確保Java中的數據類型與數據庫中列的數據類型相匹配。例如'preparedStmt.setString(1,ID);'應該是'prepareStmt.setInt(1,ID);'! –
我改變了數據庫值爲varchar,它仍然給我的問題。該程序發誓,因此它不插入行。 –
我最初和@ Kh.Taheri有同樣的想法。在數據庫表中,您的ID列是** String數據類型還是Integer數據類型,現在它到底是什麼? **列表**實際上是否包含任何內容?測試一下。把它放到控制檯:'System.out.println(List.ID);的System.out.println(List.name); System.out.println(List.password);'等 – DevilsHnd