I have been trying to add values to a table named bill_items and this is the coding for the button "add to cart" but it shows and error saying "Unknown column Jacket in field list. What is wrong in this coding?
try {
rs = stmt.executeQuery("select * from mens_wear where Item_code = 1090;");
while(rs.next()){
icode = rs.getInt("Item_code");
p = rs.getInt("Price");
bname = rs.getString("Brand_Name");
iname = rs.getString("Item_Name");
t = rs.getString("Type");
}
rs.close();
stmt.close();
con.close();
} catch(Exception e)
{JOptionPane.showMessageDialog(null,e.getMessage());}
try {
Class.forName("java.sql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/aashita","root","1510");
stmt = con.createStatement();
int a = stmt.executeUpdate("insert into bill_items values('"+icode+"','"+t+"','"+bname+"','"+iname+"','"+p+"');");
JOptionPane.showMessageDialog(null,"Added Successfully");
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage());
}
}
It is a bad practice to not specify column names in an insert and depend on table column order. There could also be an issue with escaping of your query string if any of your values contain quotes. I would try adding the column names and using a prepared statement with parameters.
string updateText = "insert into bill_items (Item_code, Type, Brand_Name, Item_Name, Price) ";
updateText += "values (?, ?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(updateText);
stmt.setInt(1, icode);
stmt.setString(2, t);
stmt.setString(3, bname);
stmt.setString(4, iname);
stmt.setInt(5, p);
int a = stmt.executeUpdate();
Related
I'm trying to fix this one for a while but can't find the or fix the code. The error triggered when I add a auto generated 'id' which is in method.
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
int row = jTable1.getSelectedRow();
String value = (jTable1.getModel().getValueAt(row, 0).toString());
String sql = "UPDATE category SET category_name = ? WHERE category_id = "+ value;
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, CategoryNameField.getText());
pstmt.executeUpdate();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setRowCount(0);
JOptionPane.showMessageDialog(null, "Record Updated Successfully ");
DisplayTable();
conn.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
You are correctly using a prepared statement, but you should be using a positional parameter in the WHERE clause instead of concatenation:
String sql = "UPDATE category SET category_name = ? WHERE category_id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, CategoryNameField.getText());
pstmt.setString(2, value);
pstmt.executeUpdate();
The exact cause of the error has to do with your WHERE clause comparing the category_id string column against an unescaped string literal, e.g.
WHERE category_id = some_value -- should be 'some_value'
SQL will interpret some_value as referring to a column, table, etc. name. By using a prepared statement (which you alreary are doing), you let the database handle the proper escaping of the values.
Image of my table as it is when I start this program.
What I have is a mostly empty table and I am trying to assign a value to a fixed number of elements. The column I am trying to edit is "Geschlecht" and the number of rows I want to edit is "copyMaen" (~50.000 entries). I would like to only select the rows where the value of "Geschlecht" was NULL before and I would like to select the rows randomly.
I am using SQLite through a JDBC driver.
This is the first time for me working with sql. This is how I tried to do it.
try {
Statement stmt = DBController.connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Geschlecht FROM individuen WHERE Geschlecht IS NULL;");
PreparedStatement ps = DBController.connection.prepareStatement("UPDATE individuen");
while (copyMaen != 0) {
if (rs.getRowId((int) (Math.random() * ReadCSV.sumBev)) == null) {
ps.setInt(2, 0);
ps.executeUpdate();
copyMaen--;
}
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
Obviosly this throws me Errors and I am not really sure how to go on from there. Could somebody point me in the right direction?
For anybody interested this is the solution:
try {
Statement stmt = DBController.connection.createStatement();
String select = "SELECT ID FROM individuen WHERE Geschlecht is NULL ORDER BY RANDOM()" +
" LIMIT " + Integer.toString(copyMaen);
ResultSet rs = stmt.executeQuery(select);
PreparedStatement ps = DBController.connection.prepareStatement("UPDATE individuen set Geschlecht = ? WHERE ID = ?;");
// rs.beforeFirst();
int count = 0;
while (rs.next()) {
ps.setInt(1, 0);
ps.setInt(2, rs.getInt(1));
ps.addBatch();
if (count%100==0) {
System.out.println(count);
}
count++;
}
DBController.connection.setAutoCommit(false);
ps.executeBatch();
DBController.connection.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
Try this,
Below update query is enough for update all row where Geschlecht is
null.
try {
Statement stmt = DBController.connection.createStatement();
String updateTableSQL = "UPDATE individuen set Geschlecht = ? where Geschlecht IS NULL";
PreparedStatement preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setString(1, "0"); // set zero where Geschlecht null found
// execute update SQL stetement
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
I am inserting a new row in db, there is no exception in the console. But the row is not inserted into the table.
String name = request.getParameter("name");
String city = request.getParameter("city");
String country = request.getParameter("country");
String query = "INSERT INTO `test`.`student`(Name,City,Country)VALUES(?,?,?);";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.setString(1,name);
ps.setString(2,city);
ps.setString(3,country);
ps.executeUpdate();
ps.close();
No need of casting the PreparedStatement again in connecting the query. It should be like
Connection conn = getDBConnection();
PreparedStatement ps = con.prepareStatement(query);
Remove the ; from the query inside the doublequotes
Prefer concatenation operator ( + sign) while using single quotes inside double quoted strings in the query
Here is a sample code that I have tested and working fine. Compare it with your code to know what you are doing wrong.
public void insertRowToDB(int staffID, String first_name, String last_name, int department_ID) {
Connection dbConnection = null;
try {
dbConnection = DatabaseConnection.getconnection();
if (!dbConnection.isClosed()) {
String sql = "INSERT INTO staff (staffID,first_name,last_name,department_ID) VALUES(?,?,?,?)";
PreparedStatement statement = dbConnection.prepareStatement(sql);
statement.setInt(1, staffID);
statement.setString(2, first_name);
statement.setString(3, last_name);
statement.setInt(4, department_ID);
statement.executeUpdate();
}
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (dbConnection!=null) {
if (!dbConnection.isClosed()) {
dbConnection.close();
}
}
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
A priori view of your code, there is no the commit statement.
You need to perform this statement right before the ps.close() line.
Best regards!
So I have a method that looks up a foreign key in a database. If the foreign key does not exist it will add an entry into the database. Now what I am doing from that point after inserting the new record, is re-querying again to get the foreign key. Is this overkill or is this the right way to do this? Thanks
private String getTestType(TestResult testResult) {
String testTypeId = "";
String query = String.format("SELECT id FROM test_types WHERE " +
"name='%s'", testResult.getTestType());
try {
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
} else {
st = con.prepareStatement("INSERT INTO test_types (name, " +
"created_at) VALUES (?, ?)");
st.setString(1, testResult.getTestType());
st.setTimestamp(2, new java.sql.Timestamp(System
.currentTimeMillis()));
st.executeUpdate();
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
}
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("There was an issue getting and or creating " +
"test Type");
}
return testTypeId;
}
Since you are inserting a new row into DB, you have to do a query to get back the auto increment field(id). Currently they way you are doing is workable. But there are few alternatives in query:
Obtaining the id using last_insert_id():
rs = st.executeQuery("select last_insert_id() as last_id");
id= rs.getString("last_id");
Another approach can be doing the MAX over the id column of the table.
I believe these are will be much faster than your query as you are doing string comparison in where clause.
So far I have been able to insert data into my SQL table only when i declare values inside the executedUpdate statement. What I wanted to know if there is a way that I can pass those values as variables that I will declare as parameters in the executing method like so:
public void updateSQL(String name, String dnsName, String ipV4, String ipV6, int statusCode)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://servername;database=databasename;integratedSecurity=true");
System.out.println("Database Name: " + connection.getMetaData().getDatabaseProductName());
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID)" + "VALUES(#Name, #DNSName, #IPAddressV4, #IPAddressV6, #StatusCodeID)");
System.out.println("Data Inserted");
ResultSet resultSet = statement.executeQuery("SELECT Name FROM ComputerStatus");
while(resultSet.next())
{
System.out.println("Computer Name: " + resultSet.getString("Name"));
}
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
System.err.println("Problem Connecting!");
}
}
I've tried couple of different things but no luck so far. Anyone know if this can be done?
You may use PreparedStatement instead of Statement.
PreparedStatement stmt = connection.prepareStatement("insert into test (firstname, lastname) values (?, ?");
stmt.setString(1, name);
stmt.setString(2, lname);
stmt.executeUpdate();
Using this way, you prevent SQL injection.
Have a look here :
PreparedStatement prep = conn.prepareStatement("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID) VALUES(?, ?, ?, ?, ?)");
prep.setString(1, name);
prep.setString(2, dnsName);
prep.setString(3, ipV4name);
prep.setString(4, ipV6);
prep.setInt(5, statusCode);
prep.executeUpdate();
this will help you understand.