JDBC does not Inserting data into mysql table - java

I have problem with inserting data into mysql table. JDBC doesnt inserting data into mysql table.
JDBC should get value from input "liczbaUzytkownikow" and "data from table form which contains informations about "termin" (Exactly: termin.nazwaObiektu, termin.adresObiektu, termin.dzien, termin.odKtorej and termin.doKtorej).
Here is code of this JDBC:
conn = ConnectionClass.Polacz();
ArrayList<Rezerwacja> rezerwacje = new ArrayList<Rezerwacja>();
PreparedStatement st = null;
ResultSet rs = null;
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
try
{
st = conn.prepareStatement(sql);
rs = st.executeQuery();
while(rs.next())
{
Rezerwacja rezerwacja = new Rezerwacja();
rezerwacja.setLiczbaUczestnikow(rs.getInt(1));
rezerwacja.setIdTermin(rs.getInt(2));
rezerwacje.add(rezerwacja);
}
}
catch(SQLException e)
{
System.out.println(e);
}
Any suggestions ?

You should use PreparedStatement to avoid sql injection attacks.
Furthermore your sql is wrong:
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
you cannot execute two different statements in a single batch.
In your case an Insert and an Update.
Create two PreparedStatement's:
String sql1 = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values (?,?)";
String sql2 = "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = ?";
PreparedStatement preparedStatement1 = con.prepareStatement(sql1);
preparedStatement1.setString(1, liczbaUczestnikow );
preparedStatement1.setInt(2, idTerminal);
PreparedStatement preparedStatement2 = con.prepareStatement(sql2);
preparedStatement2.setInt(1, idTerminal);
preparedStatement1.executeUpdate();
preparedStatement2.executeUpdate();

Related

Why am I getting this error: E/ERROR: The executeQuery method must return a result set.?

I'm trying to connect my project with an SQL-Server database. But I always get this error E/ERROR: The executeQuery method must return a result set.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String username = "un";
String password = "pass";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);
Log.w("Connection","open");
String sql = "INSERT INTO TABLE" +
"(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
"VALUES ('" + informacao.getNomeCliente() + "', '" + informacao.getNome() + "', '" + informacao.getEmail() + "', '" + informacao.getSatisfacao() + "', '" + informacao.getNota() + "') ";
Statement stmt = conn.createStatement();
ResultSet rSet = stmt.executeQuery(sql); // error here
I tried to change stmt.executeQuery to stmt.executeUpdate, but it underlines it red, and says that the output is int, so it is incompatible.
Using PreparedStatement is much safer.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String username = "un";
String password = "pass";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);
Log.w("Connection","open");
String sql = "INSERT INTO TABLE" +
"(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
"VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, informacao.getNomeCliente())
pstmt.setString(2, informacao.getNome())
pstmt.setString(3, informacao.getEmail())
pstmt.setString(4, informacao.getSatisfacao())
pstmt.setString(5, informacao.getNota())
int result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
I think you should use the executeQuery method while querying tables in the database (when you have the SELECT keyword). When you want to execute SQL statements (like INSERT, UPDATE and others) you should use execute method, as seen in here.
In your case you could try:
Boolean rSet = stmt.execute(sql);

string parameter and SELECT prepared statement for sql in java

i have a problem >>
programming language: java
Data base: Mysql database
i write a java code for retrive the record from the database based on the data parameters comping from the method>>
the code is:
public static void Get_patient_data(String Hospital1_ID,String Hospital2_ID {
try {
Connection con = getConnection2();
PreparedStatement statement = (com.mysql.jdbc.PreparedStatement)
con.prepareStatement(
"SELECT PatientGender "+
"FROM patientcorepopulatedtable "+
"WHERE PatientID = Hospital1_ID LIMIT 1" );
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while( result.next()) {
System.out.print("the patient Gender is" +
result.getString("PatientGender"));
}
}
catch(Exception e) {
System.out.println("Error"+e);
}
}
As you see the problem is Hospital1_ID parameter .. is coming from the method and the patientID is a column in a table patientcorepopulatedtable ...
the = equal operator doesn't work.
Try this
String query =
"SELECT PatientGender FROM patientcorepopulatedtable "+
" WHERE PatientID = ? LIMIT ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, Hospital1_ID);
preparedStmt.setInt (2, 1);
preparedStmt.executeQuery();
you can do it this way
PreparedStatement statement = (com.mysql.jdbc.PreparedStatement)
con.prepareStatement(
"SELECT PatientGender FROM patientcorepopulatedtable "+
"WHERE PatientID = ? LIMIT 1");
statement.setString(1, Hospital1_ID);
ResultSet result = statement.executeQuery();
you can find more info here

Get the query plan using jdbc PreparedStatement on sql server

Using Statment, resultSet.getObject returns query plan as xml
Connection conn = getConnection();
String query = " SET SHOWPLAN_XML on ";
Statement st = conn.createStatement();
boolean execute=st.execute(query);
log.info("execute status {} " , execute);
query = " SELECT ATMPROFILES.TERMID as COLUMNID, ATMPROFILES.TERMID as COLUMNNAME FROM ATMPROFILES (NOLOCK) "
+ " WHERE Authprocessname = 'ATMST' "
+ "ORDER BY ATMPROFILES.TERMID ";
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
Object object = rs.getObject(1);
log.info("Query Plan {} ", object);
}
But If I execute the same through PreparedStatement, it returns actual result insteadof QueryPlan
Connection conn = getConnection();
String query = " SET SHOWPLAN_XML on ";
PreparedStatement ps = conn.prepareStatement(query);
boolean execute = ps.execute();
log.info("execute status {} " , execute);
query = " SELECT ATMPROFILES.TERMID as COLUMNID, ATMPROFILES.TERMID as COLUMNNAME FROM ATMPROFILES (NOLOCK) "
+ " WHERE Authprocessname = 'ATMST' "
+ "ORDER BY ATMPROFILES.TERMID ";
ps=conn.prepareStatement(query);
execute=ps.execute();
log.info("execute status {} " , execute);
ResultSet rs = ps.getResultSet();
while(rs.next())
{
Object object = rs.getObject(1);
// here it returns selected object
log.info("Query Plan {} ", object);
}
Any idea to acheive this via PreparedStatement.
I haven't found any reference why executing SET SHOWPLAN_XML ON as a prepared statement will not work; however, you should get the desired results when you run this statement directly and your actual query as a prepared statement. In code:
Connection conn = getConnection();
String showplanQuery = "SET SHOWPLAN_XML ON";
Statement st = conn.createStatement();
st.execute(showplanQuery);
String actualQuery = "SELECT ATMPROFILES.TERMID FROM ATMPROFILES (NOLOCK) ";
PreparedStatement ps=conn.prepareStatement(actualQuery);
ps.execute();
ResultSet rs = ps.getResultSet();
while(rs.next())
{
Object object = rs.getObject(1);
// should log the query plan
log.info("Query Plan {} ", object);
}
Hope that helps.

How to use dynamic table name in SELECT query using JDBC

I have 5 or table table to query from \
my syntax i like this
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
When i output the sql using system.out.println(sql2);
values are not set in sql2
When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery();
String sqlStatment = "SELECT * FROM " + tableName + " WHERE Patient_ID = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sqlStatment);
preparedStatement.setint(1, patientId);
ResultSet resultSet = preparedStatement.executeQuery();
public void getByIdEmployer() throws SQLException {
Connection con = null;
try {
con = jdbcUtil.connectionDtls();
PreparedStatement ptst = con.prepareStatement(getById);
ptst.setInt(1, 4);
ResultSet res = ptst.executeQuery();
while (res.next()) {
int empid = res.getInt(1);
System.out.println(empid);
String name = res.getString(2);
System.out.println(name);
int salary = res.getInt(3);
System.out.println(salary);
String location = res.getString(4);
System.out.println(location);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
}
}

Querying to Oracle DB through JDBC gives null while direct query gives the output

I have a sql query which when I manually sends to an Oracle DB through SQLDeveloper Application gets me the output I want. But the same query returns nothing while I try to connect and query through JDBC driver why this is happening so. Please help me.
code:
String sql = "select * from tablename where id='" + id + "' AND case_id = '" + case_id + "'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
System.out.println("next = " + rs.next());
output:
select * from tablename where id='1' AND case_id = '1000'
next = false
Both connections (JDBC and SQLDeveloper) are using same username and password. So no issue of privilege or security i think.
Try to pass the "id" as a number. As you are passing the ID as String, the JDBC driver will convert it to CHAR, VARCHAR, or LONGVARCHAR.
String sql = "select * from tablename where id=" + id + " AND case_id = '" + case_id + "'";
Resulting string:
select * from tablename where id=1 AND case_id = '1000'
Consider to use PreparedStatement with bind parameters, to avoid sql injection:
String sql = "select * from tablename where id = ? AND case_id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, 1);
ps.setString(2, "1000");
ResultSet rs = ps.executeQuery();
References:
http://docs.oracle.com/javase/6/docs/technotes/guides/jdbc/getstart/mapping.html
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html

Categories

Resources