I am trying to connect a Java program to IBM's DB2 database, here is the code
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
Connection db2Conn = DriverManager.getConnection("jdbc:db2://localhost:50000/N","R","k");
Statement st=db2Conn.createStatement();
st.executeUpdate("INSERT INTO NTTP VALUES('MANOJ SAINI','iskcon110','Rajasthan','Male','july 2 2014','C')");
I get a syntax error at Statement st = db2Conn.createStatement();
Type mismatch: cannot convert from java.sql.Statement to java.beans.Statement
and more at st.executeUpdate(), as Multiple markers at this line
- The method executeUpdate(String) is undefined for the type Statement
- Syntax error, insert ";" to complete Statement
- Syntax error, insert "AssignmentOperator Expression" to complete
Assignment
- MANOJ cannot be resolved to a variable
- Syntax error, insert ";" to complete Statement
- Syntax error, insert ")" to complete MethodInvocation.
I am new to DB2 and can not figure out what is wrong.
Your SQL syntax might work in a SQL REPL, but in Java those aren't valid String(s) - also you need to escape \ because it's a special character in Java,
java.sql.Statement st=db2Conn.createStatement();
st.executeUpdate(
"INSERT INTO NTTP VALUES('MANOJ SAINI','iskcon110',"
+ "'Rajasthan','Male','july 2,2014',"
+ "'C:\\Users\\Ramveer\\Documents\\res')");
Also, you should consider using PreparedStatement and bind parameters.
First of all the error suggest that you are trying to import Statement from java.beans.Statement instead of java.sql.Statement and second thing try using java.sql.PreparedStatement instead of java.sql.Statement
Something like this :
String sql = "INSERT INTO student(student_id,student_name,class) VALUES(?,?,?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, 7);
statement.setString(2,"MANOJ SAINI");
statement.setString(3,"Rajasthan");
Related
Here's my query:
select *
from reg
where indexno=?
or tel=?
And here's my code:
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://url","unam","pass");
String query = "select * from reg where indexno= ? or tel=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, in.getText());
ps.setString(2, tl.getText());
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Let's take a closer look at what your code is doing.
Connecting to the database:
Connection con =DriverManager.getConnection("jdbc:mysql://url","unam","pass");
Creating the SQL query:
String query = "select * from reg where indexno= ? or tel=?"`;
Creating a prepared statement:
PreparedStatement ps = con.prepareStatement(query);
Setting some bind parameter values:
ps.setString(1, in.getText());
ps.setString(2, tl.getText());
Creating a whole new non-prepared statement (wait, what? Why are we not using the prepared statement we spent some time creating?):
Statement st = con.createStatement();
Using the new non-prepared statement to execute the SQL query.
ResultSet rs = st.executeQuery(query);
As a result of the last two lines, your SQL query is sent straight to the MySQL database. MySQL doesn't understand what the ? marks are for, and hence complains with a syntax error about them.
When handling prepared statements, JDBC drivers will either replace the ? marks with the database's own syntax for bind parameters (unless the database supports ? marks directly, but not all databases do), or put the values directly in the SQL string after suitable escaping of any characters, before they send the SQL to the database. Statements don't support bind parameters, and will just send the SQL string they are given straight to the database.
Your code creates a PreparedStatement and sets two bind parameter values. It seems a shame not to actually use your prepared statement once you've created it. You can get the result set you want out of it by calling ps.executeQuery(). There is no need for the separate Statement you created by calling connection.createStatement().
The fix therefore is to remove the last two lines of the code in your question and add the following line in place of them:
ResultSet rs = ps.executeQuery();
I have problem with executing query in my Java program. Here is the code:
String selected=offersList.getSelectedValue();
String sql="SELECT * from outcoming_offers where about='"+selected+"'";
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
And when there is single quotes in 'selected' - it is giving me an error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near.....
So I understand why there is error but I am wondering how to make this work. Are there any other ways except concat()?
It's always better approach is to use prepared statements instead of raw SQL string concatenation.
From your example you should write prepared query like below (parameter to pass are replaced with question marks):
String sql="SELECT * from outcoming_offers where about=?";
PreparedStatement ps = con.preparedStatement(sql);
And then just inject parameter values and execute query:
ps.setString(1, selected);
ResultSet rs = ps.executeQuery();
Thanks to this approach you don't have to deal with SQL query string and single quotes, which is very often error-prone and also (very important) your code is not expose to SQL Injection attacks.
More info in documentation: https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html
You are using a Prepared Statement but not passing the required parameter as you should. Change the statement to this:
String sql="SELECT * from outcoming_offers where about=?";
and then pass the parameter:
pst=con.prepareStatement(sql);
pst.setString(1, selected);
This way you set selected as the 1st parameter of the Prepared Statement.
Now you can execute the query:
rs=pst.executeQuery();
I was trying to add details to table but it showing some SQL error
Query is:
t=st1.executeUpdate("insert into stdetails(regno,nam,cid,gender,HouseName,place,guardian,phone,photo,did,Emailid,sem) values("+ reg+",'"+ n +"',"+ c +",'"+g+"','"+ h+"','"+p+"','"+ guar +"','"+ph+"','"+pic+"',"+d+",'"+e+"',"+s+"");
Error is
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 '' at line 1
Your are missing the parentheses ) in the end of your query so it should look like :
t = st1.executeUpdate("...." + s + ")");
//----------------------------------^---
BUT
Instead of using this way, this can cause a syntax error like your case, and can cause an Sql Injection you have to use PreparedStatement.
there is error in your mysql syntax
String query="insert into stdetails (regno,nam,gender) values(?,?,?)";
PreparedStatement preparedStmt2 = con.prepareStatement(query);
preparedStmt2.setInt (1," ");
preparedStmt2.setString (2," ");
preparedStmt2.setString(3, " ");
preparedStmt2.execute();
like this you can add more columns also
I am using a JDBC connection to fetch data from an Access database.
The database design is not my control. In the database there are columns that have "?" included in their names, for example: Open?, Paid?, and lots more.
When I try to fetch data with a PreparedStatement it gives me an error. The query is:
SELECT Open? FROM tblJobList WHERE WeekEnding=?
I also tried to use brackets like [Open?], but the result is the same.
The error I receive is "Too few parameters ..." as I am pushing only one parameter into the PreparedStatement.
I can not use normal statement because of WeekEnding=? as this value is a Timestamp and I could not manage to work it with Statement. Only prepared statement works here.
Can anyone tell me how to use these kind of column names in a PreparedStatement?
use the " character
"SELECT \"Open?\" FROM tblJobList WHERE WeekEnding=?"
tested this against oracle and appears to work with mssqlserver
How to select a column in SQL Server with a special character in the column name?
Just to update this for current technologies:
While the JDBC-ODBC Bridge and Access ODBC were unable to handle a PreparedStatement with a column name containing a question mark, the UCanAccess JDBC driver handles it just fine, as can be confirmed with the following code:
String connectionUrl = "jdbc:ucanaccess://C:/Users/Public/UCanAccessTest.accdb";
Connection conn = DriverManager.getConnection(connectionUrl);
String sql = "SELECT ID, [Open?] FROM tblJobList WHERE WeekEnding=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, java.sql.Date.valueOf("2016-01-01"));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.printf("%d: %s%n", rs.getInt("ID"), rs.getBoolean("Open?"));
}
conn.close();
For more information on UCanAccess, see
Manipulating an Access database from Java without ODBC
I am not sure but you can try // to escape the special meaning of ? and to use it as a normal character. Like:
"SELECT Open//? FROM tblJobList WHERE WeekEnding=?"
You can get something similar to your problem here:
Round bracket in string with JDBC prepared statement
Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.
What is wrong with the following statement?
String sql = "INSERT INTO tablename (colname) VALUES ($tag$$${a{e^i\\pi}a}$$$tag$);";
Connection connection = DB.getConnection();
Statement st = connection.createStatement();
st.executeQuery(sql);
After execution, there should be a new row int tablename, with $${a{e^i\pi}a}$$ in colname (type: text). But all I get is $${ae^i\pia}$$, that is the expected without the braces.
I tested it in Java 7.11, PostgreSQL 9.1 (x64) on a Windows 7 machine.
Just use prepared statements so you will never have errors with unescaped Strings because SQL does that for you automatically.
st = conn.prepareStatement("INSERT INTO tablename (colname) VALUES (?)");
st.setString(1, "$${a{e^i\\pi}a}$$");
st.executeUpdate();
For additional information you can look at the answer to this question:
Java - escape string to prevent SQL injection
This is caused by the driver's JDBC escaping e.g. to support the {call ...} or {fn ...} syntax.
According to this thread:
http://postgresql.1045698.n5.nabble.com/plpgsql-function-comment-with-single-quote-braces-td5155934.html
you need to call statement.setEscapeProcessing(false) to prevent the driver to parse JDBC escape syntax.
Note that this only happens when using dollar quoting. String literals inside "regular" single quotes are not subject to JDBC escapes (just as values for PreparedStatements)