Java PreparedStatement doesn´t set value - java

I´m totally new to Java and I try to set up a little test to read some data from a MSSQL-database. I have to pass some values to the query but that does not work properly, if I set them manually it works, in my case with the PreparedStatement and the .setLong-Method it does not work.
public class db_testClass {
public static void main(String[] args) throws ClassNotFoundException {
long firstId = 0;
long lastId = 201801001010010403L;
PreparedStatement statement;
int counter = 1;
String SQL = "IF OBJECT_ID('tempdb..#tmpDaten') IS NOT NULL
" DROP TABLE #tmpDaten;
" SELECT DISTINCT
" RIGHT(10000000 + ISNULL(r.xxx, 0), 7) AS Wert
" INTO #tmpDaten
" FROM dbo.xxx
" WHERE r.xxxx BETWEEN firstId = ? AND lastId = ?;
" SELECT DISTINCT
" 'xxxx' AS Art ,
" t.xxx
" FROM #tmpDaten
" LEFT JOIN xxxxxxx a ON a.xxxx = t.xxxx
" AND a.ART = 'xxxx' " +
" WHERE a.xxxx IS NULL;";
String connectionUrl = "jdbc:sqlserver://xxxxxx:1433;databaseName=xxxxxx;integratedSecurity=true;";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try {
Connection con = DriverManager.getConnection(connectionUrl);
statement = con.prepareStatement(SQL);
statement.setLong(1, firstId);
statement.setLong(2, lastId);
System.out.println(statement);
ResultSet rs = statement.executeQuery();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
The error says that there is wrong syntax nearby the '='......
Anyone any ideas?
Thanks,
Daniel

Your usage of the BETWEEN operator is suspicious and probably just an outright syntax violation. It should be something like:
something BETWEEN low-value AND high-value
to test if the something lies between the values low-value and hi-value.

Related

Java ResultSet Skipping Records

After a morning of research, I'm stumped on what should be an easy piece of code.
All I want is to get all records from our raw_material table in the test database.
Here is what I am doing:
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0");
do {
String result = rs.getString("raw_material_number").toString();
System.out.println("next item: " + result);
//ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Here are the results in mySQL:
so I would expect the first 'result' to be MAN-500-121200000, but it is showing as RAW-001485
I cannot see anywhere in the code that I am 'skipping' the first record, but if I let it go, it will skip the next one to MAN-500-056100000
Am I using the wrong user connection? That is the only thing I can see that affects this.
I thought user.getConnection() would do it for just the regular test database.
Your code seems to be incorrect, the expected loop is rather:
while(rs.next()) {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
Consider using try-with-resources statement to close properly your Connection, Statement and ResultSet as next:
try (Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0")) {
// My code here
}
Try like this.
while(rs.next()){
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
int i = 1;
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rsCount = st.executeQuery("SELECT COUNT(*) from raw_material");
rsCount.first();
long r = (Long) rsCount.getObject(i);
for (i=1; i < r+1; i++) {
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id =" + i + "");
//moves to the first record
rs.first();
do {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Hacky way of doing it but it got it to work for now, at least until the senior developer returns from bereavement. Keep in mind I've had only 3 months of java, baptism by fire. lol.

BatchUpdateException: Unknown column in where clause

When writing to a mySQL db, i get the following error:
java.sql.BatchUpdateException: Unknown column 'ALFA' in 'where clause'
this is my java code:
public void pushWinner(String game, String teamW) throws SQLException{
String[] t1 = game.split("-");
String statement = "update games set winner=(?) where team1 = "+t1[0]+" AND team2 = "+t1[1];
try (PreparedStatement pstmt = conn.prepareStatement(statement)) {
pstmt.setString(1, teamW);
pstmt.addBatch();
pstmt.executeBatch();
pstmt.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
I realy can't see what's wrong with the where clause...
EDIT
See my comment, forgot to mention what 'ALFA' is.
Data types for team1 and team2 are both VARCHAR(45).
try this: since datatype of column team1 and team2 are VARCHAR so put single quote to compare it.
queryString= "update games set winner=(?) where team1 = '"+t1[0]+"' AND team2 = '"+t1[1]+"'";
If your datatype is string that you need Single Quote around your passed variable values
something like this...
String statement = "update games set winner=(?) where team1 = '"+t1[0]+"' AND team2 = ' "+ t1[1] + "'";
Your asking for trouble making sql like this. use a prepared statement with seperate parameters instead of inline param building. will stop issues like this and take care of parameter escaping. So use ? in the main sql to denoate location of a parm and use .setString(1, value); to set first (yes its 1 based). Or setInt(1, intValue) ... depending on data type. For date use java.sql.Timestamp - can convert a calendar to date and java.util.Date to sql timestamp OR new javax.time or joda. But dont use inline.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Why
ease of programming and
https://www.owasp.org/index.php/SQL_Injection
Copied from the java tutorial :
String updateString =
"update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement =
"update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? " +
"where COF_NAME = ?";
try {
con.setAutoCommit(false);
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
updateSales.executeUpdate();
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
updateTotal.executeUpdate();
con.commit();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch(SQLException excep) {
JDBCTutorialUtilities.printSQLException(excep);
}
}
} finally {
if (updateSales != null) {
updateSales.close();
}
if (updateTotal != null) {
updateTotal.close();
}
con.setAutoCommit(true);
}
}

i want to display special characters from mysql to jtextfield using jbutton.my code is working only numbers

private void jbutton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
MainClass mc=new MainClass();
Connection connection;
connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd);
ResultSet rs;
String StrQr="";
if (prid.getText().trim().length()>0 )
{
StrQr=StrQr + " and pid = " + prid.getText().trim() + " ";
}
if (StrQr.length()==0)
{
JOptionPane.showMessageDialog(null,"Enter search critaria.");
return;
}
PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid");
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"connected");
while (rs.next()) {
purcst.setText(rs.getString("ppurcst"));
salprc.setText(rs.getString("psalprc"));
prid.setText(rs.getString("Pid"));
prname.setText(rs.getString("Pname"));
category.setText(rs.getString("Pcategory"));
cprc.setText(rs.getString("Pcmprc"));
qnty.setText(rs.getString("Pqty"));
slno.setText(rs.getString("Pslno"));
lpurcst.setText(rs.getString("plpurcst"));
}
rs.close();
}
catch (Exception e)
{
System.err.println(e);
//System.exit(1);
}
}
code display only pid = 104 like numbers .
it cant display special charectors( _,- )pid= A_1103like anybody can help me.
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'A' in 'where clause'
i declare pid as varchar in mysql
A_1103 needs to be quoted, otherwise MySQL will try and resolve it to a column value.
... pid = 'A_1103' ...
In fact, you should be relying on PreparedStatement in order to prevent possible SQL injection problems.
See Using Prepared Statements for more details
For example...
Connection connection;
connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd);
ResultSet rs;
// I'm assuming there are other elements to this query that
// may be included, otherwise this is a lot of overhead
// for little benifi...
List values = new ArrayList(5);
String StrQr="";
if (prid.getText().trim().length()>0 )
{
StrQr += " and pid = ? ";
values.add(prid.getText().trim());
}
if (StrQr.length()==0)
{
JOptionPane.showMessageDialog(null,"Enter search critaria.");
return;
}
PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid");
// Bind the values to the parameters
for (int index = 0; index < values.size(); index++) {
st.setObject(index + 1, values.get(index));
}
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"connected");
In prepared statement you have to set a ? or any parameter and bind the value.
String StrQr="";
if (prid.getText().trim().length()>0 )
{
StrQr=StrQr + " and pid = ? ";
}
...
PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid");
if (prid.getText().trim().length()>0 )
st.bind(1prid.getText().trim() )
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"connected");

Java mysql, Simple update with PreparedStatement has syntax error

This code has some sort of simple syntax error. I've fought it for hours now and I give up. Can you spot it? I bet it's easy. Thanks!
When I update just the firstname John, no problem.
When I try to update the commented out line for the lastname too, syntax error.
import java.sql.*;
public class UpdateTester {
public static void main(String[] args) {
try {
Connect connect = new Connect();
Connection connection = connect.getConnection();
try {
String sql = "UPDATE student SET firstName = ? "
+ " WHERE studentID = 456987";
//String sql = "UPDATE student SET firstName = ? "
// + " Set lastName = ?, "
// + " WHERE studentID = 456987";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, "John");
//pst.setString(2, "Johnson");
pst.executeUpdate();
System.out.println("Updated Successfully!");
connection.close();
} catch (SQLException e) {
System.out.println("Exception 1!");
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("Exception 2!");
e.printStackTrace();
}
}
}
Column names are correct.
Updating just the lastname on it's own works correctly too.
Update fails with syntax error when trying to do both, as in the commented out lines.
3 issues:
The SET keyword can only appear once in an UPDATE statement:
Comma before second parameter missing
Unnecessary comma before where clause
The corrected syntax:
String sql = "UPDATE student SET firstName = ?, "
+ " lastName = ? "
+ " WHERE studentID = 456987";
SQL Reference

Nested SELECT Query Java + MySQL

I'm trying to get data from DB.
I must use to queries.
From the first query (In Loop) I get the code of Work codew and the I use it in the second query to get names.
Here's the code works without errors.
The first query fetch rows but the second is not executed.
int i=0;
c= new Connect().getCon();
try{
java.sql.Statement st = c.createStatement();
String sql= " SELECT distinct(s.codew), title, nberstat, desc_w, dated,datef" +
" FROM work w, employe e, stat s " +
" WHERE w.codew=s.codew " +
" and s.idemploye= e.idemploye " +
" and stat_w=0 " +
" and w.idcreator= 1";
System.out.println(sql);
ResultSet res = (ResultSet) st.executeQuery(sql);
String allW ="";
while (res.next())
{
String codew = res.getString("codew");
String title = res.getString("title");
String desc_w = res.getString("desc_w");
String dated = res.getString("dated");
String date = res.getString("datef");
int nberstat = res.getInt("nberstat"); String strnberstat = Integer.toString(nberstat);
///////////////////////////////////
try
{
java.sql.Statement st2 = c.createStatement();
q="SELECT distinct (name), lname From stat s, employe e WHERE codew LIKE '"+codew+"'";
ResultSet res2 = (ResultSet) st2.executeQuery(q);
while (res2.next())
{
String name = res.getString("name");
String lname = res.getString("lname");
allW = name + " "+lname+", "+allW;
}
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
}
/////////////////////////////
........
}
c.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
I get this in the console for the second query! SQL code does not execute.
Thanks in advance.
Best regards,
Ali
First of all you should use PreparedStatement with sql parameters "?" to prevent Sql injections.
Secondly, you are using the wrong statement in the second loop. You should be using res2 not res.
This should be:
String name = res2.getString("name"); //not res
String lname = res2.getString("lname"); //not res
Thirdly, you should add a finally{} block and close your connection.

Categories

Resources