When trying to insert the value of a string into my db using JDBC instead of inserting the String's value it inserts the String's name.
I have a string named firstName, the value of this string is given by user input.
Here is my sql statement:
String sql = "Insert INTO users (ID, firstName, address) VALUES ('124','+firstName()','123')";
For various reasons, it is better to use java.sql.PreparedStatement. to execute statements with parameters. For example, if you want to avoid sql injection attacks.
See the examples in Using Prepared Statements from The Java Tutorials.
The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it.
PreparedStatement pstmt = conn.prepareStatement(
"UPDATE EMPLOYEES SET FIRST_NAME= ? WHERE ID = ?");
pstmt.setString(1, "user1080390"); // set parameter 1 (FIRST_NAME)
pstmt.setInt(2, 101); // set parameter 2 (ID)
int rows = pstmt.executeUpdate(); // "rows" save the affected rows
Try this
String sql = "Insert INTO users (ID, firstName, address) VALUES ('124','"+firstName()+"','123')";
To prevent sql injections, you need to escape the string before using in a query or try the prepared statements.
Something like this..
String firstName ="sample";
String sql = "Insert INTO users (ID, firstName, address) VALUES ('124',"+firstName+",'123')";
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'm parsing through some data all in a text files. By parsing it i throw everything into a String array and then use that array to insert into my MySQL database. Most of the data is actually text strings but some are dates and integers.
If i insert a string like "4538762" into a MySQL column defined as an INT will that be accepted?
Same goes for date.
It depends on how you are running your insert.
You SHOULD be running it as a PreparedStatement. When you use prepared statements you add values based on their datatype. See the example below. There is a good tutorial that you should check out at: http://tutorials.jenkov.com/jdbc/preparedstatement.html
String sql = "update people set firstname=? , lastname=? where id=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "Gary");
preparedStatement.setString(2, "Larson");
preparedStatement.setLong (3, 123);
int rowsAffected = preparedStatement.executeUpdate();
You could either pass the string as is :
preparedStatement.setString(1, "4538762") ;
or convert it to int and pass the int :
preparedStatement.setInt(1, Integer.parseInt("4538762")) ;
MySQL can handle both. In the former case, it would parse the String to int by itself.
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)