I am trying to complete my Java Code to execute a SELECT Query that will write the Results into Sysout.
Here is my Code:
public void PullFromDB() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
String sql = "SELECT * FROM " + Name + ";";
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
Integer ID = rs.getInt("id");
System.out.println("ID = " + ID.toString());
String entry = rs.getString(Properties.get(j));
System.out.println(Properties.get(j) + "=" + entry);
j++;
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
When I sysout my SQL Query it looks like this:
CREATE TABLE IF NOT EXISTS Cars(ID INTEGER PRIMARY KEY AUTOINCREMENT,AnzSitze TEXT,Marke TEXT,Pferdestärke TEXT);
INSERT INTO Cars(AnzSitze,Marke,Pferdestärke) VALUES('vier','Audi','420');
SELECT * FROM Cars;
Those are just some examples I put in.
maybe create and propabley insert has failed, i see none-ascii characters in filed name Pferdestärke try to use valid names
check this
Permitted characters in unquoted identifiers:
ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar,
underscore)
Extended: U+0080 .. U+FFFF
so replace the filed name Pferdestärke to Pferdestarke in all qrys and try again
Related
Im trying to check if a entry is set, so for example in a row with: user, password, birth
I check if in column user f.e. "mxrlin" is
For that im using that code in my Main Class:
if(!mySQL.isSet(tableName, "houseNumber", houseNumberStr)){
System.out.println(house.getHouseNumber() + " not set yet");
inserts.add(new BetterMySQL.KeyValue("houseNumber", houseNumberStr));
mySQL.insertEntry(tableName, inserts);
}else {
System.out.println(house.getHouseNumber() + " set -> updating");
mySQL.update(tableName, inserts, "houseNumber", houseNumberStr);
}
And the mySQL.isSet() method looks like this:
public boolean isSet(String tableName, String key, String value){
Check.checkNotEmpty(tableName);
Check.checkNotEmpty(key);
Check.checkNotEmpty(value);
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE ?=?", Arrays.asList(key, value));
try {
if(resultSet.next()){
return resultSet.getObject(value) != null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
But with this code it always debugs me "house.getHouseNumber() + " not set yet", so the Class doesnt find the entry that is set
You can't bind a parameter to a column name. The key in this case will be treated as a string literal in SQL.
Assuming a method call like this:
mySQL.isSet("houses", "houseNumber", "2335")
this code:
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE ?=?", Arrays.asList(key, value));
Will generate a SQL statement equivalent to
SELECT * FROM houses WHERE 'houseNumber'='2335'
Of course, the string 'houseNumber' will never equal the string '2335', so no results will be returned.
You'll need to substitute key into the SQL string, just like tableName already is:
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE " + key + "=?", Arrays.asList(value));
I am trying fetch data based on a condition on committee column using jdbc.Using Statement it produces the desired result but using PreparedStatement it does not.I cannot figure out what has gone wrong.Kindly help.Here is both the programs one using Statement and the other one using PreparedStatement and my table structure as well
import java.sql.*;
class SelectPrepared {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "abcd","abcd");
String sql = "select * from tatuserinfo where committee = 'GENERAL'";
Statement stmt = con.createStatement();
// stmt.setString(1,"GENERAL");//1 specifies the first parameter in the query
ResultSet myRs = stmt.executeQuery(sql);
while (myRs.next()) {
System.out.println(myRs.getString(1) + myRs.getString(2) + myRs.getString(3) + myRs.getString(4)
+ myRs.getString(5) + myRs.getString(6) + myRs.getString(7) + myRs.getString(8));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
import java.sql.*;
class SelectPreparedOne {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String s = "GENERAL";
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "abcd","abcd");
String sql = "select * from tatuserinfo where committee = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, s);// 1 specifies the first parameter in the query
ResultSet myRs = stmt.executeQuery();
while (myRs.next()) {
System.out.println(myRs.getString(1) + myRs.getString(2) + myRs.getString(3) + myRs.getString(4)
+ myRs.getString(5) + myRs.getString(6) + myRs.getString(7) + myRs.getString(8));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Table structure
USERNAME VARCHAR2(40)
PASSWORD VARCHAR2(40)
ROLE VARCHAR2(40)
NAME VARCHAR2(40)
DESIGNATION VARCHAR2(40)
DEPARTMENT VARCHAR2(40)
EMAILID VARCHAR2(40)
COMMITTEE CHAR(15)
TL/DR: don't use char use varchar2
CHAR(15) gets blank padded to 15 characters, so the column contains the value 'GENERAL ' and that's not equal to the supplied value of 'GENERAL'
The correct fix is to change the column to VARCHAR2(15)
An intermediate ugly workaround (until you fix the column definition) is to use trim:
where trim(committee) = ?;
I created a class (ValidarStatusOsPage) in java that makes a connection to the DB and returns to a test class (ValidateStatusOsTest) the result of the query and prints to the screen.
When I run the test class, the Eclipse console displays the message:
ORA-00923: FROM keyword not found where expecte
I have reviewed the code several times but I can not verify where the error is.
Below is the Java class for connecting to the DB and the test class.
public class ValidarStatusOsTest {
static String query;
#Test
public void validarOs() {
ValidarStatusOsPage os = new ValidarStatusOsPage();
query = os.returnDb("179195454");
}}
public class ValidarStatusOsPage {
String resultado;
public String returnDb(String NuOs) {
// Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"
String dbUrl = "jdbc:oracle:thin:#10.5.12.116:1521:desenv01";
// Database Username
String username = "bkofficeadm";
// Database Password
String password = "bkofficeadmdesenv01";
// Query to Execute
String query = "SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +"";
try {
// Load mysql jdbc driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl, username, password);
// Create Statement Object
Statement stmt = con.createStatement();
// Execute the SQL Query. Store results in ResultSet
ResultSet rs = stmt.executeQuery(query);
// While Loop to iterate through all data and print results
while (rs.next()) {
String NU_OS = rs.getString(1);
String CD_ESTRATEGIA = rs.getString(2);
String CD_STATUS = rs.getString(3);
String NU_MATR = rs.getString(4);
String DT_ABERTURA = rs.getString(5);
resultado = NU_OS + " " + CD_ESTRATEGIA + " " + CD_STATUS + " " + NU_MATR + " " + DT_ABERTURA + "\n";
System.out.println(NU_OS + " - " + CD_ESTRATEGIA + " - " + CD_STATUS + " - " + NU_MATR + " - "+ DT_ABERTURA);
}
// closing DB Connection
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return resultado;
}}
3 points are there in your query:
SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +""
space before FROM missed first part of query is: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM
space missed before WHERE: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM tb_bkoffice_osWHERE NU_OS =
concatenate parameter into SQL string is exact hack point for SQL Injection attack. Never do it in real program even if it is pure standalone. Always use parameters for queries.
and a little last one: + NuOs +"" - last "" has no sense at all...
good luck.
UPD: #YCF_L absolutely right use Prepared statement.
you need to do this:
in Sql String: WHERE NU_OS = ?
in code:
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, NuOs);
//also works: stmt.setObject(1,NuOs);
things to remember with JDBC:
all parameters in SQL are just ? marks
parameter indexes start with 1 (not 0)
and in order they appear in SQL from strat to end
(e.g. Select * FROM tbl WHERE col1=? and col2=?
has parameter 1 for col1 and parameter 2 for col2
PS. your initial SQL has one more error but I'm not going to tell you what is it :-) use parameter and all be fine.
I have code like this
String sql_kode_kategori = "select kategori from data_kategori \n" +
"where kode_kategori = ?";
try{
pst = (PreparedStatement) koneksiMySQL.GetConnection().prepareStatement(sql_kode_kategori);
pst.setString(1, (String)cbKategori.getSelectedItem());
rst2 = pst.executeQuery();
rst2.next();
stat = (Statement) koneksiMySQL.GetConnection().createStatement();
String sql_insert = "INSERT INTO data_pasal VALUES ('"+jTPasal.getText() + "','"+jTIsi_Pasal.getText()+"'"
+ ",'"+jTHukuman.getText()+"','"+jTDenda.getText()+"','"+rst2.getString(1)+"')";
stat.executeUpdate(sql_insert);
javax.swing.JOptionPane.showMessageDialog(null, "Data CES Berhasil Ditambahkan");
ClearField();
TampilTabel();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
i tried to get kode_kategori with kategori but that error appear, please help me
If rst2.next() returns false, there is no data for rst2.getString(1). You need to check for result as
if(rst2.next()) {
stat = (Statement) koneksiMySQL.GetConnection().createStatement();
String sql_insert = "INSERT INTO data_pasal VALUES ('"+jTPasal.getText() + "','"+jTIsi_Pasal.getText()+"'"
+ ",'"+jTHukuman.getText()+"','"+jTDenda.getText()+"','"+rst2.getString(1)+"')";
stat.executeUpdate(sql_insert);
} else {
// handle invalid category
}
Remove \n from your query:
String sql_kode_kategori = "select kategori from data_kategori where kode_kategori = ?";
Try to verify this (String)cbKategori.getSelectedItem() variable does contain right value.
I have the stored procedure in SQL Sever and it has a few parameter. I would like to give the value of parameter from the combo box (in java application). I've read this code (look at below)
public static void executeSprocInParams(Connection con) {
try {
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");
pstmt.setInt(1, 50);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();
pstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
But i didn't get the meaning. Is there any tutorial that give me some example just like in my case? Thanks for any reply
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");
pstmt.setInt(1, 50);
ResultSet rs = pstmt.executeQuery();
1) Line 1 creates a prepare statement object with your Stored Procedure. The ? is the placeholder for the input parameter to the Stored Procs
2) Line 2 sets the input param to the stored proc
3) executeQuery executes the stored proc by providing the input and get the output as a resultset.
while (rs.next()) {
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();
pstmt.close();
Above lines iterate over the result set and print each record
public static void executeSprocInParams(Connection con) {
try {
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");//Creating a prepared statement with the string to execute your procedure.
pstmt.setInt(1, 50);//This is to set the parameter to the place holder '?'
ResultSet rs = pstmt.executeQuery();//This is to execute your procedure and put the result into a table like set
while (rs.next()) {//To check if there are any values in the set, if so the print those values
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();//close the set
pstmt.close();//close the statement
}
catch (Exception e) {
e.printStackTrace();
}
}