Java PreparedStatement:com.microsoft.sqlserver.jdbc.SQLServerException:parameter index out of range - sql-server

I'm try to execute a SQL query using java PreparedStatement in JAVA 8 and code blow
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(URl,user,"");
String sql = "Select Grade from XS_KC where Snum=? and Cnum=?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, "020101");
pst.setString(2, "102");
rs = pst.executeQuery();
while(rs.next())
{
System.out.print(rs.getString(1));
}
I get the fllowing error:com.microsoft.sqlserver.jdbc.SQLServerException:parameter index out of range
But if i use
stat = con.createStatement();
rs = stat.executeQuery("Select Grade from XS_KC where Snum='020101' and Cnum='101'");
I can get the result
What's wrong??

The first ? in your query is Unicode 0x1FFF rather than 0x3F00 (question mark). Try:
String sql = "Select Grade from XS_KC where Snum=? and Cnum=?";

Related

Change ResultSet to TYPE_SCROLL_INSENSITIVE in Scala

I'm using Scala to connect to a database. The connection is working and I can execute SQL with the output stored in a ResultSet. I now need to change the ResultSet to TYPE_SCROLL_INSENSITIVE so that I can point to specific rows in the ResultSet. This is a section of my code (connection details omitted for data privacy):
import java.sql.{Connection, ResultSet, SQLException, Statement}
object test extends App {
def connectURL (): java.sql. Connection = {
val url = "connection url"
val username = sys.env.get("USER").get
val password = sys.env.get("PASS").get
Class. forName ( "driver name" )
var connection = java.sql.DriverManager. getConnection ( url , username , password )
connection
}
val query = "SELECT * FROM TABLE1"
val con : java.sql. Connection = connectURL (); // creates the connection
val st = con . createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE); // creates connection statement
val rs = st.executeQuery(query); // executes the query and stores as ResultsSet
}
This gives the error: overloaded method value createStatement
The con variable is of type Connection, st is of type Statement and rs is of type ResultSet. I've tried changing val to the types above, and I get this error: value st is not a member of object java.sql.Statement
Any help would be much appreciated.
Please see javadocs https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html
createStatement is defined with either 0,2, or 3 parameters

Second Order SQL Injection - PreparedStatement

The following section of my code is raising concern in "Second-Order SQL Injection".
private String function1 (String var1) {
String sql = "SELECT field1 FROM table1 WHERE field2 = ?";
PreparedStatement ps = null;
ResultSet resultSet = null;
String result = "";
try{
ps = conn.prepareStatement(sql);
ps.setString(1, var1);
resultSet = ps.executeQuery();
if(resultSet.next()){
result = rs.getString("fldDesc");
}
}catch(SQLException e){
e.printStackTrace();
}
}
However, as I know the preparedStatement should be safe against the 2nd Order SQL Injection, due to the separation of query and data.
Can I know why does it would raise a concern against it?

Java & SQL Server exception: The statement did not return a result set

I'm creating an insurance management system for my DBMS project in university, and I am having a problem with deleting a record from SQL Server. It throws an exception:
SqlException: com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
It also successfully deleted a record from my database. Could anyone please tell me how to remove this kind of exception?
String SQL="delete from INMS_3 where Agent_Id=? and First_Name=? and Last_Name=? and User_Name=? and Phone_no=?";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=INMS;user=TestingUser;password=1234;";
Connection con = DriverManager.getConnection(connectionUrl);
System.out.println("Connected to sql server");
String str=jTextField1.getText();
String str1=jTextField2.getText();
String str2=jTextField3.getText();
String str3=jTextField4.getText();
String str4=jTextField5.getText();
PreparedStatement st = con.prepareStatement(SQL);
st.setString(1, str);
st.setString(2,str1);
st.setString(3,str2);
st.setString(4,str3);
st.setString(5, str4);
ResultSet rs = st.executeQuery();
if(rs.next());
{
JOptionPane.showMessageDialog(null,"Deleted Succesfully");
}
if(!rs.next())
{
JOptionPane.showMessageDialog(null,"Unable to delete");
}
else
{
JOptionPane.showMessageDialog(null,"Unable to delete");
}
} catch (SQLException e) {
System.out.println("SQL Exception: "+ e.toString());
} catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
I think you are using the wrong thing to perform the delete operation.
Try using st.executeUpdate() instead of ResultSet rs = st.executeQuery() - you are executing a delete rather than something that would return a result set.
This is not a problem with SQL Server. The problem is with your code (what is that? C#? The object is set to expect a result set from the server, but the query is a DELETE statement, and those return no rows... ever.
State the programing language, and research for how to execute statement instead requesting result sets.
This line makes sense for a SELECT not for an UPDATE
ResultSet rs = st.executeQuery();
if you're executing a delete statement, why are you executing
ResultSet rs = st.executeQuery();
Here's a sample c# ado.net. concept it the same if you're using java.
using(var conn = new SqlConnection("my connection string"))
{
var deleteCmd = new SqlCommand();
deleteCmd.Connection = conn;
deleteCmd.CommandType = CommandType.Text;
deleteCmd.CommandText = #"
DELETE Accounts
WHERE account_id = #p_account_id
";
deleteCmd.Parameters.AddWithValue("p_account_id", 123);
conn.Open();
deleteCmd.ExecuteNonQuery();
}

Informix IfmxStatement.getSerial() to PostgreSQL substitute

Could you help me, because I have a problem? My task is to port a database from Informix to PostgreSQL, but someone use IfmxStatement method getSerial(), and I can't find any substitute for it in PostgreSQL.
Integer serial = new Integer(((IfmxStatement) stmt.getSerial());
You can use getGeneratedKeys() which is part of JDBC
stmt.executeUpdate("INSERT INTO ...", Statement.RETURN_GENERATED_KEYS);
// retrieve the auto generated key/keys
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next())
{
int serial = rs.getInt(1);
}
Thank you, this is my solution.
int serial=0;
ResultSet rs = null;
String query="SELECT nextval('id_seq');";
try
{
rs=stmt.executeQuery(query);
if (rs.next())
{
serial = rs.getInt(1);
}
setId(serial);

JDBC - prepareStatement - How should I use it?

I saw this example somewhere:
rs = connection.prepareStatement("select * from table").executeQuery();
Could I use this format, if I want to execute a query like this "Select * from table where column = "hello" "?
The way in which I usual I use prepareStatement object is something like this:
String sql = "select * from adresa where column = ?";
PreparedStatement pre = con.prepareStatement(sql);
pre.setString(1, i);
rs = pre.executeQuery();
Later Edit:
I don't understand. Pascal Thivent wrote that I can use the short version with In parameters, but Liu tells me this is not possible. :) Anw, using Pascal's version, i receive this error: void cannot be dereferenced
Here's a partial example how to use this interface:
static final String USER = "root";
static final String PASS = "newpass";
Connection conn = DriverManager.getConnection(myUrl, USER, PASS);
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into students (ID, last_name, first_name, birthday, hometown)"
+ " values (?, ?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, 808027);
preparedStmt.setString(2, "Davis");
preparedStmt.setString(3, "Felicita");
preparedStmt.setDate(4, startDate);
preparedStmt.setString(5, "Venice");
// execute the preparedstatement
preparedStmt.execute();
conn.close();
You can only use the first form if there are no bind variables (question marks) in the query. It's just a shortened version of what you posted.
Also, if you use the shortened form you won't have the opportunity to reuse the PreparedStatement object.
of course u can use a string variable for the query in which u put in ur dynamic data and run it.
rs = connection.prepareStatement(variable).executeQuery();
The long form is often, but prepared statements can be precompiled by the db, and if used properly will help prevent sql injection.
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
conn = getConn();
ps = conn.prepareStatement("select * from x where y = ? "); //note no sb.append()'s or +'s, to helps prevent sql injection
ps.setLong(1, 12l);
rs = ps.executeQuery();
while (rs.next()) {
... act ...
}
} catch ( Exception e) {
} finally {
if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();
}
Who said java was verbose. :)

Resources