String sql = "INSERT INTO Student_Info(name,roll_no,address,phone_no) VALUES('101', 1, 'Fatma', '25')";
String sql = "insert into Student_Info(name,roll_no,address,phone_no) VALUES("+student.getName()+","+student.getRoll_no()+","+student.getAddress()+","+student.getPhone_no()+")";
the last query shows an error:
java.sql.SQLException: ORA-00917: missing comma
at
statement.executeUpdate(sql);
Can anyone rule out where am I missing the comma?
You miss the single quotes around student.name, student.address and student.phone_no
String sql = "insert into Student_Info(name,roll_no,address,phone_no) VALUES('"+
student.getName()+"',"+
student.getRoll_no()+",'"+
student.getAddress()+"','"+
student.getPhone_no()+"')";
Do notice that this sql statement is vulnerable for sql injection attacks. Use a PreparedStatement.
String sql = "insert into Student_Info(name,roll_no,address,phone_no) " +
"VALUES(?,?,?,?)";
addStudent = con.prepareStatement(sql);
addStudent.setString(1, student.getName());
addStudent.setInt(2, student.getRoll_no());
addStudent.setString(3, student.getAddress());
addStudent.setString(4, student.getPhone_no());
addStudent.executeUpdate();
con.commit();
Do it in this way:
String sql = "insert into Student_Info(name, roll_no, address, phone_no)
VALUES(?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, value); // indexing starts from 1 (not from zero)
...
ps.executeUpdate();
// commit if you have set auto-commit to false
Never use raw statements but PreparedStatements1. Raw statements have lower performance, are more vulnerable (SQL Injection attacks) and what is most important is readability of code that is on very low level (especially in case if you have more columns).
1PreparedStatements are much more safer, pre-compiled, have better performance and are user-friedly readable and more...
rene's answer is correct. I would like to add, however:
It is much better practice to use Prepared Statements
Your code would look something like:
String sql = "INSERT INTO Student_Info(?,?,?,?) VALUES(?,?,?,?)"
PreparedStatement sql_prepared = connection_object.prepareStatement(sql)
Related
I have raw insert query like
insert into sample(id, name) values(1, 'text \\N\');
Getting SqlException while trying to insert via jdbc but the same insert query is working if I insert via mysql command prompt(console).
jdbc insert query is failing due to special characters("\N") in name field.
so how to overcome and insert the name with \N?
The cleanest approach is to not use a raw SQL query at all. If, as you've stated, you receive the name from some other process then it is presumably in a String variable (or property, or similar) so you can simply use a parameterized query to perform the insert:
// example data
int theId = 1;
String theName = "the name you received from somewhere else";
//
PreparedStatement ps = conn.prepareStatement("INSERT INTO sample (id, name) VALUES (?, ?)");
ps.setInt(1, theId);
ps.setString(2, theName);
ps.executeUpdate();
How can I update my SQL Table column with the value that is stored in a local variable.
In my program I have taken value from the HTML page using the following statement:
String idd=request.getParameter("id");
String report=request.getParameter("rprt");
So now I have to update the value of report in my database table named "ptest" and I am using the following query:
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root");
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("update ptest set result = #reprt where patient_id=
#idd");
out.println("Successfully Entered");
But the value is not being stored in the database instead NULL is being stored.
I have already seen this question and got no help.
Question
Please ignore my mistakes if any in this question as I am new to MYSQL.
You can use prepared statements in java.
setString or setInt can set different data types into your prepared statements.
The parameter 1, 2 are basically the positions of the question mark. setString(1,report) means that it would set the string report in the 1st question mark in your query.
Hope this code helps you in achieving what you want.
String query = "update ptest set result = ? where patient_id = ?";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, report);
preparedStatement.setString(2, idd);
preparedStatement.executeUpdate();
In JDBC, you use ? as placeholders for where you want to inject values into a statement.
So you should do something like this ...
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root");
PreparedStatement st= con.prepareCall("update ptest set result = ? where patient_id=
?");
///now set the params in order
st.setString(1, report);
st.setString(2, idd);
//then execute
st.executeUpdate();
Doing a string concat with the values is dangerous due to sql injection possibilities, so I typically make statement text static and final, and also if your value has a ' in it that could blow up your sql syntax etc. Also, notice the use of executeUpdate rather than query.
Hope this helps
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,"+u+","+p+",'1')");
I'm getting the error
java.sql.SQLException: Unknown column '(the U variable)' in 'field list';
I know for sure it is 100% the "" but i can't seem to find it where it goes wrong
any help is appreciated!
This is my whole method (I want to learn how to do it with a prepared statement)
public static void connectionDB(String u, String p, String f){
{
try {
String username = "/////////";
String password = "///////";
String url = "///////////////";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Database connected!");
}
}
It should be like
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
Update:-
You can also look into prepared statements because
Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.
Assuming fields are A,B,C,D;
A is int and remains are strings
String insertTableSQL = "INSERT INTO Leden"
+ "(A,B,C,D) VALUES"
+ "(?,?,?,?)";
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "Hello");
preparedStatement.setString(3, "this");
preparedStatement.setString(4, "OP");]
preparedStatement .executeUpdate();
It should be
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')'");
The issue is, that " is used in SQL for objects like columns or tables, whereas ' is used for strings. So in +u+, which seems to not exists in context of your query.
Your query itself should therefore look something like (given, that +u+ and +p+ are strings.
INSERT INTO Leden VALUES (null,'+u+','+p+','1')
If you need to have " inside your columns, it would read like
INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')
Also I would recommend to specify the columns you are inserting to so it looks similar to:
INSERT INTO "Leden" ("col1", "col2", "col3", "col4") VALUES (null,'+u+','+p+','1')
This will prevent your query from failing when extending table definition by another column.
Also using prepared statements could be a good idea here, as it helps you preventing from e.g. SQL injections.
I was updating password in an oracle databse using a java servlet like this
Connection con;
PreparedStatement ps,ps1;
ResultSet rs;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException e)
{
System.out.println("Drivers Not Found");
}
try{
con=DriverManager.getConnection("jdbc:odbc:SharedCryptography", "fyp", "fyp");
}catch(SQLException e1)
{
}
String query="UPDATE tbGroup SET GPassword='"+mypassword+"' where GName='"+GroupNamee+"' and OEmail='"+OwnerId+"'";
java.sql.Statement stmt = con.createStatement();
stmt.executeUpdate(query);
But it gives java.sql.SQLException: [Oracle][ODBC][Ora]ORA-01756: quoted string not properly terminated
Am i doing something wrong in it?Please help
You should absolutely avoid string concatenation in SQL statements. You will get in all kind of security and stability problems. Your problem is simply be resolved by using a prepared statement:
String sql="UPDATE tbGroup SET GPassword=? where GName=? and OEmail=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, myPassword);
ps.setString(2, groupName);
ps.setString(3, ownerId);
ps.executeUpdate();
If you do this, no "'" or "%" or "_" or " in your parameters will cause any problems. Alternatively you can try to escape your characters, but why bother - the PS method is not only more robust and easier to read, it is often also more performant.
For a general description of the security problems, see: https://www.owasp.org/index.php/SQL_injection
One of your variables (probably password) has a quote or semi colon in it. Since you build up your query via String concatenation, you are vulnerable to SQL injection attacks. It looks like you accidentally attacked yourself via injection. If you had a properly maliciously formatted variables you could have done quite a bit of damage to your database.
Please use Parameterized queries
PreparedStatement stmt = con.prepareStatement("UPDATE tbGroup SET GPassword= ? where GName= ? and OEmail=?" )
stmt.setString(1, mypassword);
...
stmt.executeUpdate();
See this for more details
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
On my web site, I need to perform a wild card query with a value provided by the end user. The best practice is to use a PreparedStatement mainly to avoid SQL Injection. My query is very very long so this is an example:
String query = "SELECT ... FROM ... WHERE ..."+ //
"AND UPPER(CUST_NAME) LIKE UPPER('%?%')";
PreparedStatement pstmt = conn.prepareStatement(query);
stmt.setString(1, "joe");
The problem is the setString() throws an exception: SQL Exception: Invalid column index
Instead of using the concat operator you could use
like upper('%' || ? || '%')
slightly more readable.
Try:
String query = "SELECT ... FROM ... WHERE ..."+ //
"AND UPPER(CUST_NAME) LIKE UPPER(?)";
PreparedStatement pstmt = conn.prepareStatement(query);
stmt.setString(1, "%joe%");
Replace...
UPPER('%?%')
...with...
UPPER(?)
...then set the parameter value as:
pstmt.setString(1, "%joe%");
BTW this query has a potential for poor performance. For good performance you'll need a functional index on UPPER(CUST_NAME) ("normal" index on CUST_NAME is not enough) and you'll need to only query by prefix (e.g. "joe%"). Querying by suffix (such as "%joe" or "%joe%") cannot be sped-up by an index.