I have set up a program for an enterprise to handle their brochures(catalogo in spanish).
I ask the user via Swings for the data, and then use it to generate a query and insert it into my db.
Here is the code:
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(false);
st = con.createStatement();
String sql = "INSERT INTO `catalogos` (`id`, `name`, `keywords`) VALUES(" + catNumIn.getText() + ", '" + catNameIn.getText() + "', '" + catKeyIn.getText() + "');";
st.executeUpdate(sql);
So i would like to know what my error is. Thank you!
Are you committing your transaction? You've said setAutoCommit(false) after all. Could you try:
setAutoCommit(true);
instead of the line you currently have, or:
con.commit();
after your database update?
When you construct sql statement in your front end and have an error, the best approach is to print the variable and see if there is a problem with the values like single quotes,missing comma,etc
Related
i'm try to made a simple log in sistem with java and mysql, the configuration of the db is made up, but i have an error in the SQL sintax:
System.out.println("SISTEM LOGIN");
System.out.println("INSERIRE NOMEUTENTE");
Scanner scan= new Scanner(System.in);
String user= scan.nextLine();
System.out.println("INSERIRE PASSWORD");
String pass= scan.nextLine();
try {
boolean log = true;
while(log) {
//conn db
Connection c = DriverManager.getConnection(url,usr,pswd);
//creaz statement
Statement ss = c.createStatement();
//creaz codice sql
String sql = " SELECT * FROM users WHERE user'" + user + "' && password='" + pass+ "' ";
ResultSet res = ss.executeQuery(sql);
if(res!=null) {
System.out.println("LOGIN");
log = false;
}
else System.out.println("LOGIN FAILE");
}
}
what do you think i haven't see in the sql string?
this is the response :
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 ''ciao' && password='12'' at line 1
The following statement is wrong and should be avoided:
String sql = " SELECT * FROM users WHERE user'" + user + "' && password='" + pass+ "' ";
String concatenation makes it vulnerable to SQL injection attacks. Use preparedstatement. Look here for an example and here as well.
Moreover you are missing an = after user and replace && with AND.
And as suggested by the error, go through the mysql manual once.
Your expanded SQL statement reads
SELECT * FROM users WHERE user 'ciao' && password='12'
That's wrong. To be valid SQL it needs to say
SELECT * FROM users WHERE user = 'ciao' AND password='12'
#PritamBanerjee pointed out it's vulnerable to sql injection. That's dangerous.
And, this is horrendous for another reason. You should never, ever, store unscrambled passwords in your dbms. If you're not sure why, visit https://haveibeenpwned.com.
The php manual has a good explanation of the right way to do it. http://php.net/manual/en/faq.passwords.php You should use a one-way scrambling function like bcrypt for this purpose.
Here's some decent material about doing this in Java. https://www.owasp.org/index.php/Hashing_Java
Your query is not correct
String sql = " SELECT * FROM users WHERE user'" + user + "' && password='" + pass+ "' ";
If you will check you have included "' && password='" + pass+ "' ";
but in forst part of statement user'" + user here missing =
Correct query should be
String sql = " SELECT * FROM users WHERE user='" + user + "' && password='" + pass+ "' ";
Actually there is not any issue with the && operator as mentioned in comments : https://dev.mysql.com/doc/refman/5.7/en/non-typed-operators.html
You just missing the = operator just after the WHERE user statement.
I suggest you to use "prepared statements" when injecting parameters to your sql statement for preventing sql injection (How does a PreparedStatement avoid or prevent SQL injection?).
PreparedStatement stmt = c.prepareStatement("SELECT * FROM users WHERE user=? && password=?");
stmt.setString(1, user);
stmt.setString(2, pass);
ResultSet res = stmt.executeQuery();
I am trying to run a SQL statement in Java and I am getting syntax
String number,key; //populate number and key.
rs = stmt.executeQuery("select count(*)
from users_transition
where phoneNumber =" +number +"and randKey="+key);
In MySQL database, phoneNumber is BigInt(20) and key is Int(11).
Also, according to this link. The table 5.1 says that types in MYSQl can be converted to what types in Java. Doesnt the other way round would work too?
Here's the ERROR
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 'randKey=9999' at line 1
You are missing a space between the number and the AND operator:
rs = stmt.executeQuery("select count(*) from users_transition where phoneNumber =" +number +" and randKey="+key);
// ^
You should replace the query with prepared statement, and use query parameters. This would help you not only avoid simple errors like this, but also make your code immune to SQL injection attacks.
String sql = "select count(*) from users_transition where phoneNumber =? and randKey=?";
PreparedStatement getCount = con.prepareStatement(sql);
getCount.setBigDecimal(1, new BigDecimal(number));
getCount.setBigDecimal(2, new BigDecimal(randKey));
I'll tell you what is wrong, and then I'll tell you what is very wrong.
What is wrong
First, you are building a query which where has missing spaces (and possibly missing quotes):
String number,key; //populate number and key.
rs = stmt.executeQuery("select count(*) "
+ "from users_transition "
+ "where phoneNumber =" +number +" and randKey="+key)";
// ^ you missed a space here
What is very wrong
Your query is vulnerable to SQL Injection Attacks (please read the link, it provides a humorous example and tips on solving the problem). Use prepared statements to do this kind of thing:
String number, key;
PreparedStatement ps = conn.prepareStatement("select count(*) "
+ "from users_transition "
+ "where phoneNumber=? "
+ " and randKey=?");
// The question marks are place holders for values
// You can assign this values with setXXX() methods
ps.setString(1, number);
ps.setString(2, randKey);
ResultSet rs = ps.executeQuery();
// Do whatever you need to do with the ResultSet
I am trying to insert user information taken from a registration form into Derby DB using a java servlet class.
I get connected to the DB on NetBeans right after the user clicks the submit button with the user's information filled out. Then it should run this method:
public void insertNewUser(String userName, String passWord, String lastName, String firstName, String age, char sex, String email) {
try {
stmt = conn.createStatement();
String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES ('" + userName + "', '" + passWord + "', '" + lastName + "', '" + firstName + "', " + age + ", '" + sex + "', '" + email + "')";
System.out.println(insertNewUserSQL);
stmt.executeQuery(insertNewUserSQL);
stmt.close();
} catch(SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
But I keep getting the following exception:
java.sql.SQLException: executeQuery method can not be used for update.
What does this mean exactly?
The SQL command is correct as I can do it manually on NetBeans SQL Command window.
Are there restrictions for servlets or something I don't know about?
Thanks in advance!
Since you are inserting a record, you should be using executeUpdate() not executeQuery().
Here are some methods that are usually misused:
boolean execute()
Executes the SQL statement in this PreparedStatement object, which may
be any kind of SQL statement.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns
the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which
must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement
that returns nothing, such as a DDL statement.
One more thing, your query is weak as it is vulnerable with SQL Injection. Please do parameterized by using PreparedStatement.
Sample Code Snippet:
String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(insertNewUserSQL);
pstmt.setString(1, userName);
// ... repeat this step until the last parameter ....
pstmt.setString(7, email);
pstmt.executeUpdate();
Java PreparedStatement
To update values you need to use an updatable ResultSet, as follows:
ResultSet res = preparedStatement.executeQuery(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
res.first();
res.updateInt("id", 2);
res.updateRow();
Alternatively, you can use the executeUpdate method of statement, as follows:
statement.executeUpdate("update table set id = 2");
I made a simple insert into statement but it is not working well. The error that it gives to me is
com.mysql.jdbc.exceptions.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 'From, To, Message,
Date, Read) VALUES (3,1,'iepa','2012-10-16 16:26:42',0)' at line 1
this is the code of my sql.
Connection conn = Connect.getConnection();
try{
Statement stmt = conn.createStatement();
String sql = "INSERT INTO MESSAGE("
+ "From,"
+ "To,"
+ "Message,"
+ "Date,"
+ "Read) "
+ "VALUES(?,?,?,?,?)";
PreparedStatement pstat = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstat.setInt(1, user.getId());
pstat.setInt(2, Integer.parseInt(who.getText().toString()));
pstat.setString(3, message.toString());
pstat.setTimestamp(4, new Timestamp(new Date().getTime()));
pstat.setInt(5, 0);
pstat.executeUpdate();
As you see I am not doing nothing strange or so difficult but I cannot run it.
You need to escape reserved words in MySQL like from with backticks
String sql = "INSERT INTO MESSAGE("
+ "`From`,"
+ "`To`,"
+ "Message,"
+ "Date,"
+ "`Read`) "
+ "VALUES(?,?,?,?,?)";
Change From,Read and Date to any other column name which is not a SQL keyword.
Find list of Reserved Words in MySQL
Iam using a Java Swing Application to Update a column in Mysql table. Here is My code(part)
String qunty = txtWithdraw.getText();
String partno = txtNo.getText();
int qty = Integer.parseInt(qunty);
con = DriverManager.getConnection(url + db, "username", "password");
Statement st = con.createStatement();
String sell = "update Store_info_table set qnty_received = qnty_received - " + qty + "where Part_number = '" + partno + "'";
st.executeUpdate(sell);
I am getting the Exception that:
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 'Part_number = 'DF6534'' at line 1
I want to Update the qnty_received field so that it is equal to the Original value minus the value passed by the user i.e (int qty). What Error Am I making?
Add a space before the where:
" where Part_number = '" + partno + "'";
As a good practice, I recommend you to use PreparedStatement and set your parameters with the same. Concatenating the parameters dynamically may force the db engine to parse a new SQL statement every time.
A SQL statement is precompiled and stored in a PreparedStatement
object. This object can then be used to efficiently execute this
statement multiple times.
See: PreparedStatement
Missing space:
... + qty + "where ...
^--- here
which makes your query something like
... qnty_received - blahwhere