Update MySQL table row [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
Hi, I wanted to add a Password change function to my programm. For that i need to update the password column of the specific user. I researched about it and fount this and tried it:
UPDATE uprtable SET password = '"+password+"' WHERE username = '"+username+"';
I also found out that i need to select the row after it. So I did this too.
SELECT username, password FROM uprtable WHERE username '"+username+"';
The Problem is it doesnt update it and I dont get any Errors where I could get any Info about what is wrong.
Here is the Code direct from the Class:
public void changepw() throws Exception{
Connection con = getConnection();
String passwordID1 = String.valueOf((passwordfield.getPassword()));
String passwordID2 = String.valueOf((passwordfield2.getPassword()));
String passwordID3 = String.valueOf((passwordfield3.getPassword()));
if (passwordID1.equals(resultSet.getString("password"))) {
if (passwordID2.equals(passwordID3)) {
String userID = resultSet.getString("username");
try {
PreparedStatement statementpwchange = con.prepareStatement("UPDATE uprtable SET password = '"+passwordID2+"' WHERE username = '"+userID+"'");
PreparedStatement statementpwchangeconfirm = con.prepareStatement("SELECT username, password, rank FROM uprtable WHERE username = '"+userID+"'");
System.out.println("Updated");
frame.dispose();
}
catch(Exception e){
System.out.println(e);
}
}
else {
messageLabel.setForeground(Color.RED);
messageLabel.setText("The Passwords do not match");
}
}
}
If you need more Information about the Code, feel free to ask.
Thank you in advance!

You have prepared the statement but have not executed the statement. For reference: INSERT (as well as UPDATE and DELETE) statements should use executeUpdate().
SELECT statements should use executeQuery().

Related

Why is my SQL Query only selecting the last entry in a column [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to connect to SQL Server from an Android app and after days of struggling, I have finally figured it out. Now I have run into a much simpler problem. My select query only selects the last value from the table. The table only contains string values for now as it is a test table. Here is what I wrote in my code.
public void sqlButton(View view) {
if (connection != null) {
Statement statement = null;
try {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("Select * from [dbo].[Table_1];");
while (resultSet.next()) {
textView.setText(resultSet.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
else {
textView.setText("Connection is null");
}
}
Your problem is probably that you're overwriting your output text each time.
Write this to a multiline text field, so you see all results:
textView.setText(textView.getText() + "\n" + resultSet.getString(1));
Actually, the select query returns all records in your table. However, the problem is in this part
while (resultSet.next()){ textView.setText(resultSet.getString(1));}
the text in the next loop will replace one in the previous. Therefore, you only see the last one.

How I properly prepare JDBC PreparedStatment? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I started to work at my own Minecraft plugin. I need database connection to do so. I try to execute query and I get errors that I can't find solutions for.
Here is the code of function that I'm using:
public void checkIfUserExists(String login, Connection connection) {
String query = "SELECT login FROM edvault.users WHERE login = ?";
try {
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, login);
ResultSet rs = statement.executeQuery();
if (!rs.next()){
String query2 = "INSERT INTO edvault.users (login) VALUES ?";
PreparedStatement statement2 = connection.prepareStatement(query2);
statement2.setString(1 , login);
int result = statement2.executeUpdate();
if (result != 1){
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "<DBINFO> ERROR OCCURRED WHILE INSERTING NEW USER" +
" TO DATABASE");
} else {
Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "<DBINFO> ADDED NEW USER TO DATABASE : LOGIN - "+
login);
}
} else
Bukkit.getConsoleSender().sendMessage("<DBINFO> USER ALREADY EXISTS IN DATABASE");
} catch (SQLException e) {
e.printStackTrace();
}
}
And here is the exception that console returns to me (this is exception for the first query, where login is xEdziu):
[22:26:21] [Server thread/WARN]: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'xEdziu' in 'where clause'
Replace
INSERT INTO edvault.users (login) VALUES ?
with
INSERT INTO edvault.users (login) VALUES (?)

App crash when try to connect to DB with JDBC [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to get some values from my database, but when I click button (void ButtonClick) my app crashes.
That's my code:
public void ButtonClick() throws Exception {
getConnection();
}
public Connection getConnection() throws Exception {
try {
String username = "*******";
String password = "*******";
String url = "jdbc:mysql://http://**.***.***.***:3306/UserDB";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = (Connection) DriverManager.getConnection(url,username,password);
Statement statement = (Statement) conn.createStatement();
String query = "SELECT * FROM TABLE 'UserDB'";
ResultSet result = statement.executeQuery(query);
while (result.next()) {
String name = result.getString("Username");
int id = result.getInt("ID");
int points = result.getInt("Points");
Toast.makeText(this, name + " " + id + " " + points, Toast.LENGTH_SHORT).show();
}
return conn;
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
(I don't know what's the error because my AVD don't work)
Thanks for help!
Starting with Java 7, there is no need to use forName() method. You are creating a new instance in this way and in the same time you are trying to create a connection using DriverManager.getConnection().
So in order to solve this, just remove the instantiation of the driver using forName() method.
Seeing the screen-shot, please note that you can't access a MySQL database from Android natively. Actually you may be able to use JDBC, but it is not recommended. Please see this post
Hope it helps.

Invalid operation at current cursor position [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I made a Java Forum and im trying to search my sql table, when i click the button to finally search it (the name of the person) it comes up with a "Invalid Operation at Current Cursor Position" error.
Here'e my code for the search button. Please help me figure this out.
private void firstSearchActionPerformed(java.awt.event.ActionEvent evt) {
try{
String fname = searchText.getText();
Connection connect = DriverManager.getConnection("jdbc:derby://localhost:1527/Employees",
"users", "admin");
PreparedStatement pState = connect.prepareStatement("select * from WORKERS where First_Name = ?");
pState.setString(1,fname);
ResultSet rSet;
rSet = pState.executeQuery();
if(rs.next()){
int id_col = rSet.getInt("Employee_ID");
String id = Integer.toString(id_col);
String first = rSet.getString("First_Name");
String last = rSet.getString("Last_Name");
String job = rSet.getString("Title");
String hireDate = rSet.getString("Hire_Date");
textID.setText(id);
textFirstName.setText(first);
textLastName.setText(last);
textTitle.setText(job);
textHireDate.setText(hireDate);
}else{
JOptionPane.showMessageDialog(null, "Not in Database");
}
}catch(SQLException err){
JOptionPane.showConfirmDialog(employees.this, err.getMessage());
}
}
ResultSet rSet;
rSet = pState.executeQuery();
instead of
if(rs.next()){
use
if(rSet.next()){
Here resultset object is rSet not rs

Get "jdbc.SQLServerException: Incorrect syntax near ','" error when exececute PreparedStatement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I wrote some java code to insert data into SQL Server 2012's Database when the user presses a button. When I run the code, I get this error:
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near ','.
and it says that the sqlstatement.executeUpdate(); line caused the error. I know that this line is not a problem. The problem is my sql query but I cannot find how my query is wrong. Would you please help me?
Here the code
count++;
for(int count = 0; count < table_1.getRowCount(); count++){
try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection dbconbt8 = DriverManager.getConnection("" +"jdbc:sqlserver://localhost;databaseName=Store;user=sa;password=XXXXXX");
String sqlQ = "INSERT INTO [dbo].[Transaction]([TransactionID],[ProductID]"+
",[TotalPrice]) VALUES ("+count+"','"+table_1.getValueAt(count, 0).toString()+"','"+sumprice+ "') ";
PreparedStatement sqlstatement = dbconbt8.prepareStatement(sqlQ);
sqlstatement.executeUpdate();
sqlstatement.close();
dbconbt8.close();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
You are missing a single quote after VALUES ( - this should fix the problem:
String sqlQ = "INSERT INTO [dbo].[Transaction]([TransactionID],[ProductID]"+
",[TotalPrice]) VALUES ('"+count+"','"+table_1.getValueAt(count, 0).toString()+"','"+sumprice+ "') ";
-- ^
-- Here
However, this is a bad fix: you should rewrite your query with parameters, so that the problem of quoting the data becomes irrelevant altogether:
String sqlQ = "INSERT INTO [dbo].[Transaction]([TransactionID],[ProductID],[TotalPrice]) VALUES (?,?,?) ";
PreparedStatement sqlstatement = dbconbt8.prepareStatement(sqlQ);
sqlstatement.setInt(1, count);
sqlstatement.setString(2, table_1.getValueAt(count, 0).toString());
sqlstatement.setInt(3, sumprice);
sqlstatement.executeUpdate();

Categories

Resources