Update Data Records on MySQL using user input - java

Ok I have this issue. I need to update a record on my DB but I am having trouble because of my SQL syntax. By pressing the "Update Name" button, 2 messages pop up and the user selects the former name and the new name for the Table. But the statement is never executed and the names wont change. My main goal is to "resolve" the id from the 1st statement to a variable
String name_1 = "SELECT id FROM consoles WHERE name LIKE ? ";
and add it here
String name = "UPDATE consoles SET name = ? WHERE id = ?";
Is it possible to resolve to a variable the id I get from my 1st statement?
try
{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
String name_1 = "SELECT id FROM consoles WHERE name LIKE ? ";
String name = "UPDATE consoles SET name = ? WHERE name LIKE ?";
PreparedStatement psname = conn.prepareStatement(name);
PreparedStatement psname_1 = conn.prepareStatement(name_1);
String strin = JOptionPane.showInputDialog(null,"Previous Name : ");
String strout = JOptionPane.showInputDialog(null,"New Name : ");
psname.setString(1,strin);
psname.setString(2,"%" +strout+ "%");
psname_1.setString(1,"%"+strin+"%");
psname.executeUpdate();
Statement stmtname = conn.createStatement();
// show the updated table
ResultSet rsname = stmtname.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
.
.
.
ADDING THEM TO A JTABLE
.
.
.

Arguments are switched.
psname.setString(2,"%" +strout+ "%");
psname_1.setString(1,"%"+strin+"%");
should be
psname.setString(2, "%" + strin + "%");
psname_1.setString(1, strout);

try
{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
String name = "UPDATE consoles SET name = ? WHERE name LIKE ?";
PreparedStatement psname = conn.prepareStatement(name);
String strin = JOptionPane.showInputDialog(null,"Previous Name : ");
String strout = JOptionPane.showInputDialog(null,"New Name : ");
psname.setString(1,strout);
psname.setString(2,"%" +strin+ "%");
psname.executeUpdate();
Statement stmtname = conn.createStatement();
// show the updated table
ResultSet rsname = stmtname.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
.
.
.
ADDING THEM TO A JTABLE
.
.
.

Related

Can't get my jsp to store the integer value from my result set

All I am trying to do is pull the integer value from the cell. When I run the command in my sql workbench I get the proper value screenshot of db output however when I execute the code in programming environment I get "An exception occurred processing [/registration.jsp] at line [24]" which is this line idnum = rs.getInt("MAX(idnum)")+1; The program has an initial html page where the use enters the desired password, first name and last name. it then sends the info to the jsp which is supposed to take that information increment the user id by 1 from whatever the highest value is currently then create a new table entry with said information.
int idnum = 0;
String pwd = request.getParameter("pwd");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment2", "root",
"has the actual password in the code");
Statement stmt = conn.createStatement();
String query = "SELECT MAX(idnum) FROM users";
ResultSet rs = stmt.executeQuery(query);
idnum = rs.getInt("MAX(idnum)")+1;
Replace
idnum = rs.getInt("MAX(idnum)")+1;
with
if (rs.next())
idnum = rs.getInt(1)+1;
Note that without calling the next() method, the result set pointer/cursor will not move to the 1st row (from default position).
This should work:
String query = "SELECT MAX(idnum) as maxNum FROM users";
ResultSet rs = stmt.executeQuery(query);
if(rs.next(){
idnum = rs.getInt("maxNum")+1;
}

Java: Check the manual that corresponds to your MySQL server version for the right syntax to use near '?VALUES ('23')' at line 1

I am trying to update my database table but I have encountered a MySQLSyntaxErrorException. May I know how can I solve this error?
Thanks ! :)
//Retrieve data from database
String queryy = "SELECT agent.agentID, agent.agentEmail, departmentName FROM agent JOIN department ON agentEmail = email";
rs = myStat.executeQuery(queryy);
//Iterate the result set and get one row at a time
while (rs.next()) {
int id = rs.getInt("agentID");
email = rs.getString("agentEmail");
String emaill = email;
departmentName = rs.getString("departmentName");
String departmentNamee = departmentName;
System.out.println("Agent ID = " + id);
System.out.println("Department Name = " + departmentNamee);
System.out.println("Email = " + emaill + newLine);
//Update agentID in department table from agent table
String departmentUpdateSql = "UPDATE department SET agentID = ?"
+ "VALUES ('" + id +"')";
myStat.executeUpdate(departmentUpdateSql);'
And this is the error that I got:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?VALUES ('23')' at line 1
sql update statements do not use the VALUES keyword (that is for inserts)
Use a PreparedStatement as below
String updateTableSQL = "UPDATE department SET agentID = ?"
PreparedStatement preparedStatement =
dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setInt(1, id);
// execute update SQL stetement
preparedStatement.executeUpdate();
Note
I would imagine that you would also need some kind of where clause otherwise you will be updating all records

Displaying SQL select result on JAVA

How do I display SQL result with system print?
Here are my code
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/oopdb","root","12345");
st = con.createStatement();
//set query
String s = "SELECT Category FROM infocollected WHERE Adminno='123'";
//save query result into rs
rs = st.executeQuery(s);
//retrieve category from result
String category = rs.getString("Category");
//print out result to console
System.out.println("category");
while (rs.next()) {
String category = rs.getString("Category");
System.out.println(category);
}
And check if your DB is not Empty
You shouldn't surround variables with double quotes. And also take a loot at #Gatusko's answer.
Replace it with:
// ...
//retrieve category from result
String category = rs.getString("Category");
//print out result to console
System.out.println(category);
When you want to print a variable, there is no need to indicate it with "" . Just only the variable name.
For example if you use your code, your console is showing: category
However if you use System.out.println(category); your console will print the value of the variable.

How to Run Query on Long number

Hello everyone i am trying to run a simple query on a long number i have tried but still returns me id type is long integer. I am getting all the data a jTable and the 1st column is of id when i ever click on the row it always gives me this exception and i have got the correct value from table when printed in console
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
My code is :
int row = recordsTable.getSelectedRow();
String tableValue = (recordsTable.getModel().getValueAt(row, 0).toString());
String qry = "Select * from records where id ='" + Long.parseLong(tableValue) + "'";
try {
db.setStmt((Statement) db.getCon().createStatement());
ResultSet rs = ((java.sql.Statement) db.getStmt()).executeQuery(qry);
if (rs.next()) {
id=rs.getLong("id");
idTextField.setText(Long.toString(id));
customerCode = rs.getString("customer_code");
custCodeTextField.setText(customerCode);
firstName = rs.getString("first_name");
firstTextField.setText(firstName);
lastName = rs.getString("last_name");
lastTextField.setText(lastName);
customerContact = rs.getString("customer_mobile");
custMobTextField.setText(customerContact);
customerAddress = rs.getString("customer_address");
custAddressTextField.setText(customerAddress);
fillComboBox();
area=rs.getString("area");
areaComboBox.setSelectedItem(area);
payment_this_month = rs.getInt("payment");
paymentTextField.setText(Integer.toString(payment_this_month));
duePayment = rs.getInt("balance");
balTextField.setText(Integer.toString(duePayment));
java.util.Date dateSet = rs.getDate("bill_issued_on");
billTextField.setText(dateSet.toString());
connectionStatus = rs.getString("connection_status");
jComboBox2.setSelectedItem(connectionStatus);
Remove the single quotes around
'" + Long.parseLong(tableValue) + "'"

How to add a number to a field in ms access?

Im trying to add the number 1 to a certain field. How could i manage to do that? Ive tried it but i can never get it to add 1. My ms access table column is set to Number not text.
if (s2.equals(box1Text)) {
if (s3.equals(box2Text)) {
if (s5.equals(currentWinner)) {
String sql = "UPDATE Table2 "+ "SET Score = ? " + "WHERE Better = '" + s1+"'";
PreparedStatement stmt = con.prepareStatement(sql);
//points made here
if (s4.equals(betScore)) {
stmt.setString(1, "+1");//how could i add 1 to the field?
stmt.executeUpdate();
} else {
}
First you do something that is regarded as bad practice : you construct your query by adding the value of a parameter in the string.
String sql = "UPDATE... >+ s1 +<..."
Please nether do that (what is between > and <) when programming seriouly, but allways use ? to pass values.
Second, SQL can do the job for you :
String sql = "UPDATE Table2 SET Score = Score + 1 WHERE Better = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, s1);
stmt.executeUpdate();
(try, catch, tests and other details omitted for brevity)

Categories

Resources