insert into database having large number of parameter - java

i have to insert data into database .Because sql statement VALUES(......) have 8 parameters . Is it proficient way to use insert statement ?
Class UserRegistration {
public void insertToDatabase(){
String sql=" INSERT INTO db1(......) Values(id,fname,lastname,username,password,usertype,email,contact,address )"
}
}

The correct way to do it in Java, assuming you're using JDBC, is to use a PreparedStatement.
String sql = "INSERT INTO db1" +
" (id,fname,lastname,username,password,usertype,email,contact,address)" +
" VALUES (?,?,?,?,?,?,?,?,?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt (1, id);
stmt.setString(2, fname);
stmt.setString(3, lastname);
stmt.setString(4, username);
stmt.setString(5, password);
stmt.setString(6, usertype);
stmt.setString(7, email);
stmt.setString(8, contact);
stmt.setString(9, address);
stmt.executeUpdate();
}

Related

this is my code and my problem is: java.sql.SQLException: No value specified for parameter 1

public boolean findCongDan(String socancuoc) throws SQLException {
CongDan congdan = new CongDan();
openDatabase();
String sqlFind = "Find From CongDan Where SoCanCuoc = ?";
PreparedStatement stmt = jdbcConnection.prepareStatement(sqlFind);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
stmt.setString(1, socancuoc);
stmt.setString(2, congdan.getHoTen());
stmt.setString(3, congdan.getDiaChi());
stmt.setString(4, congdan.getGioiTinh());
stmt.setString(5, congdan.getNgaySinh());
stmt.setString(6, congdan.getDanToc());
stmt.setString(7, congdan.getTonGiao());
stmt.close();
}
closeDatabase();
int rowFind = stmt.executeUpdate();
return rowFind>0;
}
You didn't provide parameters for your query before executing it. You have to call setString on your prepared statement before calling executeQuery
Every ? in the query string needs to be provided in the stmt.executeQuery():
ResultSet rs = stmt.executeQuery("search value");
effectively making the query like this:
Find From CongDan Where SoCanCuoc = 'search value';

how to get the last insert id in java mysql

i am creating simple sales system. i have to get the last insert id but i couldn't get the id.when i tried the code i got the error of the console
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
i attached the code below what i tried so far
try{
int lastinsertid=0;
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con1=DriverManager.getConnection("jdbc:mysql://localhost/javasales","root","");
String query = " insert into sales_product (product, price)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = (PreparedStatement) con1.prepareStatement(query);
preparedStmt.setString (1, txtproduct.getText());
preparedStmt.setString (2, txtprice.getText());
preparedStmt.executeUpdate();
ResultSet rs = preparedStmt.executeQuery();
if (rs.next()) {
lastinsertid = (int) rs.getLong(1);
}
System.out.println("Inserted record's ID: " + lastinsertid);
}
catch(ClassNotFoundException coe)
{
System.out.println("odbc driver not found");
}
catch(SQLException sqe)
{
System.out.println(sqe);
}
You need to add Statement.RETURN_GENERATED_KEYS in con1.prepareStatement(query) that would result that you can get the generated key. You also should use only one of the following methods:
executeQuery
executeUpdate
Because there is no reason, to use booth methods.
After you done that you can get it like that:
...
PreparedStatement preparedStmt = con1.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
preparedStmt.setString (1, txtproduct.getText());
preparedStmt.setString (2, txtprice.getText());
preparedStmt.executeUpdate();
ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
if (generatedKeyResult.next()) {
lastinsertid = generatedKeyResult.getInt(1);
}
System.out.println("Inserted record's ID: " + lastinsertid);
...

Adding to table using Jdbc & ms managment system

I bumped into this problem and i cannot figure out what is wrong with this code. I use jdbc and ms managment system for the databse and its connection.
code:
try {
//create user
preparedStatement = conn.prepareStatement("INSERT INTO Users(name, pass, type) VALUES (nick=?,pass=?,type=?)",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
preparedStatement.setString(1, user.getNickName());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setInt(3, type);
rs = preparedStatement.executeQuery();
System.out.println(rs.toString());
catch (Exception e) {
System.out.println("Exception: " + e);
}
error:
Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '='.
The way you are using the ? characters is invalid in JDBC:
"INSERT INTO Users(name, pass, type) VALUES (nick=?,pass=?,type=?)
One ? represents the whole bind variable. Try
"INSERT INTO Users(name, pass, type) VALUES (?, ?, ?)"
Also, use executeUpdate to execute an insert statement (or update, or delete).
Remove the field names from the value list. These are already in the name list. Also use executeUpdate for database write operations:
preparedStatement =
conn.prepareStatement("INSERT INTO Users(name, pass, type) VALUES (?,?,?)",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
preparedStatement.setString(1, user.getNickName());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setInt(3, type);
int rowCount = preparedStatement.executeUpdate();

What am I doing wrong with this preparedStatement?

private Connection conn = DriverManager.getConnection(URL, info);
try {
String sql = "INSERT INTO \"STUD1582251\".\"ACCOUNTS\" VALUES USERNAME=?, PASSWORD=?, PORTFOLIONAME=?";
PreparedStatement stm = conn.prepareStatement(sql);
stm.setString(1, user.getUsername());
stm.setString(2, user.getPassword());
stm.setString(3, user.getPortfolioName());
System.out.println(sql);
stm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
Exception
SELECT username FROM "STUD1582251"."ACCOUNTS" WHERE username=? INSERT
INTO "STUD1582251"."ACCOUNTS" VALUES USERNAME=?, PASSWORD=?,
PORTFOLIONAME=? java.sql.SQLSyntaxErrorException: ORA-00933: SQL
command not properly ended
INSERT SQL statement must be:
String sql = "INSERT INTO \"STUD1582251\".\"ACCOUNTS\" (USERNAME,PASSWORD,PORTFOLIONAME) VALUES (?,?,?)";
PS: Use " (double quotes) around identifier if it is a reserved word.

Java using Jconnect

Good day!
In order to access the mysql server, I used the JConnect and my code is as follows:
public AddBooks() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/catalog";
conn = DriverManager.getConnection(url,"root","upittc");
stmt = conn.prepareStatement("INSERT INTO books VALUES(?,?,?,?,?,?,?,?,?,?,)");
} catch (Exception exc) {
JOptionPane.showMessageDialog(null, exc.getMessage());
}
initComponents();
}
To put the data in the database, I used the following code:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
stmt.setString(1, jTextField0.getText());
stmt.setString(2, jTextField1.getText());
stmt.setString(3, jTextField2.getText());
stmt.setString(4, jTextField3.getText());
stmt.setString(5, jTextField4.getText());
stmt.setString(6, Jan2.getSelectedItem().toString());
stmt.setString(7, Jan3.getSelectedItem().toString());
stmt.setString(8, jTextField5.getText());
stmt.setString(9, jTextField6.getText());
stmt.setString(10, jTextField8.getText());
stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "Save Successful!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
But there's an error on row 1. COLUMN COUNT DOESN'T MATCH THE VALUE AT ROW What does it mean?
Please advise. Thank you.
If the field is auto-increment, you should not assign anything to it, remove it from your SQL prepared statement string and just set everything else, the auto increment will do the job by itself.
PreparedStatement stmt = connect.prepareStatement("INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) ");
get rid of first column to have:
PreparedStatement stmt = connect.prepareStatement("INSERT INTO table_name (column2, column3,...) VALUES ( value2, value3,...) ");
and replace values with question marks and set them as you do later on.
stmt.setString(1, jTextField1.getText());
stmt.setString(2, jTextField2.getText());
stmt.setString(3, jTextField3.getText());
stmt.setString(4, jTextField4.getText());
stmt.setString(5, Jan2.getSelectedItem().toString());
stmt.setString(6, Jan3.getSelectedItem().toString());
stmt.setString(7, jTextField5.getText());
stmt.setString(8, jTextField6.getText());
stmt.setString(9, jTextField8.getText());
stmt.executeUpdate();
NOTICE: decremented indices (the number of the question mark value).
Hope that helps!

Categories

Resources