Jdbc Postgresql is not executing the query - java

I am trying to connect my android app to my postgresql database through jdbc, the login goes well but when i try run the query explotes and give me this error:
11-24 11:03:14.966: E/AndroidRuntime(673): at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:403)
11-24 11:03:14.966: E/AndroidRuntime(673): at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:283)
This is the code of the function that make the connection:
public void save_info(Element plate_info){
String retval = "";
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
retval = e.toString();
}
String url = "jdbc:postgresql://test.com:5432/test_db?user=adsfsdfasd&password=2222222";
Connection conn;
try {
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(url);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("INSERT INTO order_tbl (custumer, _name, additional, ingredients_) VALUES('adsfasdf','asdfasdfasdf', 'asdfasdfasd', 'asdfasdfasdf', 'dasfasdf')");
while(rs.next()) {
retval = rs.getString(1);
}
rs.close();
st.close();
conn.close();
System.out.println(retval);
} catch (SQLException e) {
e.printStackTrace();
retval = e.toString();
}
}

You need to call executeUpdate, not executeQuery
int numRowsAffected = st.executeUpdate("INSERT INTO order_tbl (custumer, _name, additional, ingredients_) VALUES('adsfasdf','asdfasdfasdf', 'asdfasdfasd', 'asdfasdfasdf', 'dasfasdf')");

This is all you need.
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(url);
Statement st = conn.createStatement();
st.execute("INSERT INTO order_tbl (custumer, _name, additional, ingredients_) VALUES('adsfasdf','asdfasdfasdf', 'asdfasdfasd', 'asdfasdfasdf', 'dasfasdf')");
Here's a quick tutorial on how to use SQL Insert http://www.youtube.com/watch?v=Zto0PovkbKo

Related

How to Close Statements and Connection in This Method

How to Close Statements and Connection in This Method
public static ResultSet getData (String query){
try {
Connection con = ConnectionProvider.connect();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
System.out.println(e);
return null;
}
You need to close connections in finally block:
try {
...
}
catch {
...
}
finally {
try { st.close(); } catch (Exception e) { /* Ignored */ }
try { con.close(); } catch (Exception e) { /* Ignored */ }
}
In Java 7 and higher you can define all your connections and statements as a part of try block:
try(Connection con = ConnectionProvider.connect();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
) {
// Statements
}
catch(....){}
One should use try-with-resources to automatically close all.
Then there is the p
public static void processData (String query, Consumer<ResultSet> processor){
try (Connection con = ConnectionProvider.connect();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
processor.accept(rs);
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
System.getLogger(getClass().getName()).log(Level.Error, e);
}
}
processData("SELECT * FROM USERS", rs -> System.out.println(rs.getString("NAME")));
Or
public static <T> List<T> getData (String query, UnaryOperator<ResultSet, T> convert){
try (Connection con = ConnectionProvider.connect();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
List<T> result = new ArrayList<>();
while (rs.next()) {
result.add(convert.apply(rs));
}
return result;
} catch (SQLException e) {
System.getLogger(getClass().getName()).log(Level.Error, e);
throw new IllegalArgumentException("Error in " + query, e);
}
}
Then there is the danger with this function, that users will compose query strings like:
String query = "SELECT * FROM USERS WHERE NAME = '" + name + "'";
Which does not escape the apostrophes like in d'Alembert. It opens the gates to SQL injection, a large security breach. One needs a PreparedStatement, and then can use type-safe parameters.
As with try-with-resources the code already is reduced (no explicit closes), you should drop this kind of function. But almost most programmers make this mistake.

Java - [SQLITE_BUSY] The database file is locked (database is locked)

I had a java app with mysql connection but i had to transfer my database to sqlite from mysql because of mysql can not be embedded, i have the connection but i get this exception when i am using the app.
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
I learnt this is a common mistake but i tried most of the answers however couldn't solve. The problem is i have about 30 different methods with void type or return types like these 2 for example below; (I call these methods on my swing app later)
I have these at start of my class;
private Connection con = null;
private Statement statement = null;
private PreparedStatement preparedstatement = null;
Methods for example;
public int lastPlaceProgram(){
String query= "Select * from userprogram where laststayed = 1";
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
int programid = 0;
while(rs.next()){
programid = rs.getInt("programid");
}
return programid;
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
return 0;
}
}
or
public String programType(int programid){
String query = "Select * from programs where id = ?";
try {
preparedStatement = con.prepareStatement(query);
preparedStatement.setInt(1, programid);
ResultSet rs = preparedStatement.executeQuery();
String type = "";
while(rs.next()){
type = rs.getString("type");
}
return type;
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
And constructor;
public Operations() {
String url = "jdbc:sqlite:C://Users//Me//Desktop//sqlited/trying.db";
try {
con = DriverManager.getConnection(url);
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
}
}
I tried to add these finally block to after catch blocks of all my 30 methods;
finally{
try{
con.close();
} catch(Exception e){
}
}
But it didn't work, it gave Connection is closed mistake this time. I also tried to add preparedstatement.close(); to this finally block but didn't still work.
Finally blocks didn't work for me, i closed them manually if i had that variable to close. I mean if i used ResultSet and PreparedStatement at a method then i made rs.close() and preparedstatement.close() just before catch or before return. If i just had Preparedstatement variable on the method then i just did preparedstatement.close() before catch block or before return.

JDBC connection in Java with Eclipse ( when a method calling a method)

I'm trying to connect to my DB using JDBC. I wanted to make a method for connection and another method for selecting data. I am getting a red line in Eclipse on the 'Connection con = connectDB();' part. ( See also attached) Cany anyone give me advice?
public class DBJdbc {
//Statement stmt = null;
// connecting to DB
public void connectDB() {
//Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
// a method for selecting DB
public static void select() {
//connectDB();
String sql = "SELECT * from SAC_SUR";
try(Connection con = connectDB(); // I'm getting a red line here)
PreparedStatement pstmt = con.prepareStatement(sql)){
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println("Id = " + id + "name = " + name);
} //while
} catch(SQLException e) {
System.out.println(e.getMessage());
}
}
red line here!!!
connectDB() method is of void type and not returning anything but when you are calling the method, you are assigning it to variable con. So you need to change the return type of connectDb to the Connection type.
public Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
You are trying to call non-static method into the static area, which is not allowed in Java. So I made this method static and returning the database connection.
Please update the below method into your code. It will resolve your problem.
public static Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "", "");
} catch(SQLException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}

Insert to database using web service in java

when i wrote function instead of procedure, it compiled.
CREATE OR REPLACE function ilce_gtr
(
p_ilkodu number
)
RETURN VARCHAR2 AS
p_geridonen varchar2(1000);
begin
for rec in(SELECT ADI FROM ILCE WHERE Y_IL=p_ilkodu)
loop
p_geridonen := p_geridonen || '|' || rec.ADI;
end loop;
return p_geridonen;
end;
/
then i created xml via web method, it was successful.
#WebMethod
public String get_ilce (int p_ilkodu) {
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
String deger=null;
try {
conn= getConnection_test();
String query = "SELECT ILCE_GTR('" + p_ilkodu + "') FROM DUAL";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
deger = rs.getString(1);
}
} catch (Exception e) {
return "hata";
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
return "hata";
}
}
return deger;
}
I want to do the same for inserting to database, can u help me?
#WebMethod
public String add_ilce (int yourInput) {
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
String deger=null;
try {
conn= getConnection_test();
String query = "INSERT INTO DUAL" + "(yourAttributeName)" +"VALUES (?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, yourInput);
preparedStmt.execute();
} catch (Exception e) {
return "hata";
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
return "hata";
}
}
return deger;
}
EDIT: I suggest you to use DAO approach for such scenarios, check here: Data access object (DAO) in Java
EDIT: I edited the post now it must work as it should be, sorry I had some mistakes
web service didnt appear on localhost, there are others.
#WebMethod
public String add_ilce (String p_no, int p_tplm) {
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
String deger=null;
try {
conn= getConnection_test();
String query = "INSERT INTO DUAL" + "TEMP_TAHAKKUK_AG(ABONENO,TOPLAM)" +"VALUES ('p_no','p_tplm')";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
deger = rs.getString(1);
}
} catch (Exception e) {
return "hata";
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
return "hata";
}
}
return deger;
}

while executing store procedure getting error

I have written a calling procedure but an exception is being thrown, please can you look at my code:
try
{
connection myconn = Database.Get_Connection();
CallableStatement mystmt =null;
mystmt = myconn.prepareCall("{? =call proc_hi_check_user(?,?)}");
mystmt.setString(1,name);
mystmt.setString(2,"");
mystmt.execute();
param1 = mystmt.getInt(1);
ResultSet myrs = mystmt.getResultSet();
while(myrs.next())
{
System.out.println("inside");
System.out.println(myrs.getInt(1));
//result=myrs.getString(1);
}
} catch (Exception e)
{
System.out.println("db connection not connected");
}
From what you say in your comments, you seems to be missing a sql function "proc_pandu_check_user".
Check the body of the "proc_hi_check_user", somewhere there it should call this proc_pandu_check_user and it is probably missing or has wrong argument list.
Try executing below code:
try
{
connection myconn = Database.Get_Connection();
CallableStatement mystmt =null;
mystmt = myconn.prepareCall("{? =call proc_hi_check_user(?,?)}");
mystmt.registerOutParameter(1, java.sql.Types.OTHER);
mystmt.setString(2,name);
mystmt.setString(3,"");
mystmt.execute();
param1 = mystmt.getInt(1);
ResultSet myrs = mystmt.getResultSet();
while(myrs.next())
{
System.out.println("inside");
System.out.println(myrs.getInt(1));
//result=myrs.getString(1);
}
} catch (Exception e)
{
System.out.println("db connection not connected");
}

Categories