Mysql syntax error in java [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 5 years ago.
Improve this question
i'm pretty sure that my query is correct but i get the message " you have an error in your sql syntax; check the manual that corresponds to your MySql server version for the right syntax near to 'group='aaa' and Date_de_naissanse........." at line 1 .
i checked the syntax meany times i did it in two versions but still the same message . here's my code :
if (rdps==true){
con = connection.connect();
String sql ="SELECT * FROM eleve_ps WHERE Nom_et_prenom=? and Group=? and Date_de_naissanse=? and Responsable=? and CIN=? and Telephone=? and Adresse=?";
try{
st=con.prepareStatement(sql);
st.setString(1, txtnp.getText());
st.setString(2, txtg.getText());
st.setInt(6, Integer.parseInt(txtt.getText()));
st.setString(4, txtr.getText());
st.setString(5, txtc.getText());
st.setDate(3, date);
st.setString(7, txta.getText());
rs=st.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null,"VOTRE COURRIER DEJA EXISTE");
}else{
String insert = "INSERT INTO `eleve_ms`(`ID`, `Nom_et_prenom`, `Group`, `Date_de_naissanse`, `Responsable`, `CIN`, `Telephone`, `Adresse`) VALUES (Null,'"+txtnp.getText()+"','"+txtg.getText()+"','"+date+"','"+txtr.getText()+"','"+txtc.getText()+"','"+Integer.parseInt(txtt.getText())+"','"+txta.getText()+"')";
try{
st=con.prepareStatement(insert);
st.executeUpdate();
this.setVisible(false);
}
catch(Exception e ){
JOptionPane.showMessageDialog(null,e);
}
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
rdms=false;
}
and so is this version :
if (rdps==true){
con = connection.connect();
String sql ="SELECT * FROM eleve_ps WHERE Nom_et_prenom='"+txtnp.getText()+"' and Group='"+txtg.getText()+"' and Date_de_naissanse='"+date+"' and Responsable='"+txtr.getText()+"' and CIN='"+txtc.getText()+"' and Telephone='"+Integer.parseInt(txtt.getText())+"' and Adresse='"+txta.getText()+"' ";
try{
st=con.prepareStatement(sql);
rs=st.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null,"VOTRE COURRIER DEJA EXISTE");
}else{
String insert = "INSERT INTO `eleve_ps`(`ID`, `Nom_et_prenom`, `Group`, `Date_de_naissanse`, `Responsable`, `CIN`, `Telephone`, `Adresse`) VALUES (Null,'"+txtnp.getText()+"','"+txtg.getText()+"','"+date+"','"+txtr.getText()+"','"+txtc.getText()+"','"+Integer.parseInt(txtt.getText())+"','"+txta.getText()+"')";
try{
st=con.prepareStatement(insert);
st.executeUpdate();
this.setVisible(false);
}
catch(Exception e ){
JOptionPane.showMessageDialog(null,e);
}
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}

As mentioned in comments: GROUP is a reserved word and MySQL is case insensitive.
Try this, paying attention to the back ticks surrounding the word Group.
String sql ="SELECT * FROM eleve_ps WHERE Nom_et_prenom=? and `Group`=? and Date_de_naissanse=? and Responsable=? and CIN=? and Telephone=? and Adresse=?";

Related

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 (?)

Error : java.util.ArrayList cannot be cast to java.lang.String [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
when am running my action i faced Error :
" java.util.ArrayList cannot be cast to java.lang.String "
and this is my code :
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object selected = list_1.getSelectedValue();
Connection conn = null;
PreparedStatement stmt = null;
String a =null;
try{
conn=DriverManager.getConnection("jdbc:mysql://localhost/flyer","root","000");
String query= " INSERT INTO flyer_item (discount) SELECT price * ? FROM `item` WHERE item_name = `?` ";
Statement st= conn.createStatement();
java.sql.PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1,a);
ps.setString(2,(String) selected);
ps.executeUpdate();
st.executeUpdate(query);
} catch (SQLException se){
System.out.println(se.getMessage());
} }} );
Any help please ?
Here Selected is an array-list and you are trying to convert it into string which is not possible:
ps.setString(2,(String) selected);
What you should do?
ps.setString(2, selected.tostring());
Are you sure about this line ?
Object selected = list_1.getSelectedValue();
Make sure selected is a String before casting . You can use instanceof operator to check the Object type.

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();

How to easy upload content to MySql database in Java using JDBC? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I’m beginner and I have problems with using MySql in Java with JDBC.
Can anybody paste a lines of code how to use “SQL UPDATE”.
Or maybe someone know about some good tutorials to learn it?
My code with mistakes:
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
ResultSet ra = st.executeQuery(strUpdate);
ResultSet rs = st.executeQuery("select * from rozchody");
while(rs.next()){
System.out.println("wyswietlam: ");
String s = rs.getString("nazwa");
System.out.println(s);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
For executing UPDATE/INSERT/CREATE statements you should use execute() function of Statement class and not executeQuery().
Corrected code :
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
st.execute(strUpdate); // or use executeUpdate()
It will return a boolean value that you can check and proceed.
follow this example here but this is essentially it
String strUpdate = "UPDATE rozchody SET nazwa ='test'";
PreparedStatement preparedStatement = conn.prepareStatement(strUpdate);
// execute insert SQL stetement
preparedStatement.executeUpdate();
When you want to do a UPDATE,INSERT,DELETE on a SQL database, you never receive a resultset.
Use executeUpdate instead of executeQuery.
Only one ResultSet object can be opened for a Statement. You're creating two ResultSet objects with your UPDATE and then your SELECT statements.
Since UPDATE does not return a ResultSet, use st.execute(strUpdate). Then you can retrieve a ResultSet with st.executeQuery("select * from rozchody");
Your fixed code:
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
//Change this
st.execute(strUpdate);
ResultSet rs = st.executeQuery("select * from rozchody");
//Now you won't get an error opening a new ResultSet
while(rs.next()){
System.out.println("wyswietlam: ");
String s = rs.getString("nazwa");
System.out.println(s);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
Note that while the above will work, it is generally better to use PreparedStatements rather than re-using a Statement for different executions. This will help prevent SQL injection, and you should read into it once you have a firmer grasp on how the Statement object works.

Categories

Resources