Hi I’m trying to connect to and SQLite table in java and it only outputs data from one method in the compiler output window code is below working method it commented to show which one is printing out the data please could you help.
//working methord which outputs data
#Override
public String getReplyTimestamp(int RPLYID) {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Matt\\Documents\\message.sqlite");
Statement stmt = conn.createStatement();
String query = "SELECT * FROM MSG"; //Change message to relevent declaration
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("MSG")+" "+rs.getString("URL"));
}
conn.close();
} catch (SQLException ex) {
Logger.getLogger(DBAccessImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBAccessImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return "getReplyTimestamp";
}
//Methoed which does not print
#Override
public String getReply(int RPLYID) {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Matt\\Documents\\message.sqlite");
Statement stmt = conn.createStatement();
String query = "SELECT * FROM RPLY"; //Change message to relevent declaration
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("RPLY")+" "+rs.getString("TSTAMP"));
}
conn.close();
} catch (SQLException ex) {
Logger.getLogger(DBAccessImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBAccessImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return "getReply";
}
Related
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.
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.
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;
}
I have the following code:
try {
String sql = "SELECT COUNT(*) AS \"Jumlah\" FROM dokter";
ResultSet rs = connection.st.executeQuery(sql);
if(rs.next()){
abc = rs.getString("Jumlah").toString();
}
} catch (Exception e) {
System.out.println("\n Message: " + e.getMessage());
}
Why can't my ResultSet execute the given SQL?
Lose the alias, it's just an unnecessary complication. Just reference the ResultSet by the column's index:
try {
String sql = "SELECT COUNT(*) FROM dokter";
ResultSet rs = connection.st.executeQuery(sql);
if(rs.next()) {
abc = rs.getInt(1); // or getString(1) if you need it as a String
}
} catch (Exception e) {
System.out.println("\n Message: " + e.getMessage());
}
I suggest you use a PreparedStatement and a try-with-resources to close it (and your ResultSet). A count is not a String, and if you have a Connection connection then you might do something like
int count = 0;
try {
String sql = "SELECT COUNT(*) FROM dokter";
try (PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
count = rs.getInt(1);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I had requirement to perform two insert queries in two different tables.
I am using Oracle/Java Combination.
What are the options available in this case?
If you're trying to insert the same data into two separate tables you can use a multitable insert like this:
insert all
into table1(a, b)
into table2(a, b)
select 1 a, 2 b from dual;
The most straightforward method is to do two inserts sequentially using the same connection. Assuming that part of your point is that you want the two inserts to occur in the same transaction, then make sure you have disabled autocommit on the connection, and explicitly commit after the second insert.
Another option would be to write an Oracle stored procedure that does the inserts, and call it from Java with a PreparedStatement.
Sample from devdaily.
package com.devdaily.sqlprocessortests;
import java.sql.*;
public class BasicJDBCDemo
{
Connection conn;
public static void main(String[] args)
{
new BasicJDBCDemo();
}
public BasicJDBCDemo()
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost/coffeebreak";
conn = DriverManager.getConnection(url, "username", "password");
doTests();
conn.close();
}
catch (ClassNotFoundException ex) {System.err.println(ex.getMessage());}
catch (IllegalAccessException ex) {System.err.println(ex.getMessage());}
catch (InstantiationException ex) {System.err.println(ex.getMessage());}
catch (SQLException ex) {System.err.println(ex.getMessage());}
}
private void doTests()
{
doSelectTest();
doInsertTest(); doSelectTest();
doUpdateTest(); doSelectTest();
doDeleteTest(); doSelectTest();
}
private void doSelectTest()
{
System.out.println("[OUTPUT FROM SELECT]");
String query = "SELECT COF_NAME, PRICE FROM COFFEES";
try
{
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next())
{
String s = rs.getString("COF_NAME");
float n = rs.getFloat("PRICE");
System.out.println(s + " " + n);
}
}
catch (SQLException ex)
{
System.err.println(ex.getMessage());
}
}
private void doInsertTest()
{
System.out.print("\n[Performing INSERT] ... ");
try
{
Statement st = conn.createStatement();
st.executeUpdate("INSERT INTO COFFEES " +
"VALUES ('BREAKFAST BLEND', 200, 7.99, 0, 0)");
}
catch (SQLException ex)
{
System.err.println(ex.getMessage());
}
}
private void doUpdateTest()
{
System.out.print("\n[Performing UPDATE] ... ");
try
{
Statement st = conn.createStatement();
st.executeUpdate("UPDATE COFFEES SET PRICE=4.99 WHERE COF_NAME='BREAKFAST BLEND'");
}
catch (SQLException ex)
{
System.err.println(ex.getMessage());
}
}
private void doDeleteTest()
{
System.out.print("\n[Performing DELETE] ... ");
try
{
Statement st = conn.createStatement();
st.executeUpdate("DELETE FROM COFFEES WHERE COF_NAME='BREAKFAST BLEND'");
}
catch (SQLException ex)
{
System.err.println(ex.getMessage());
}
}
}
You can check with StoredProcedures and execute with PreparedStatement in JDBC api. That intern will return you two resultSets , which you can get with a method getMoreResults(). You can then process the resultsets separately.