Hello guys so I have this simple java to do and I am trying to connect to an sqlite database from eclipse but it doesn't work at all.
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseConnection {
private String pathDB="C:\\sqlite\\test.db";
private Connection connection=null;
private Statement statement=null;
public DatabaseConnection(String path){
pathDB= path;
}
public void connect () {
try {
Class.forName("org.sqlite.JDBC");
connection= DriverManager.getConnection("jdbc:sqlite:" + pathDB);
statement= connection.createStatement();
System.out.println("Connection to " + pathDB + " "+ "successful");
} catch (ClassNotFoundException notFoundException) {
notFoundException.printStackTrace();
System.out.println("Connection Error!");
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.out.println("Connection Error!");
}
String query="Insert into Identity values(0,'issam','issam#mail.com')";
try {
statement.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close() {
try {
connection.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And the main class:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
DatabaseConnection connection= new DatabaseConnection("test.db");
connection.connect();
connection.close();
}
}
So I have this sqlite database but whenever I run the code it always gives me : Connection to "path" was successful, no matter what path I put...
I think I have done everything correctly, I downloaded the sqlite JDBC file and added it:
enter image description here
I tried adding a new row to a database table, but it always gives me this:
Connection to test.db successful
java.sql.SQLException: no such table: Identity
at org.sqlite.core.NativeDB.throwex(NativeDB.java:397)
at org.sqlite.core.NativeDB._exec(Native Method)
at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)
at com.issam.iamcore.DatabaseConnection.connect(DatabaseConnection.java:41)
at com.issam.iamcore.Main.main(Main.java:10)
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
at org.sqlite.core.DB.newSQLException(DB.java:890)
at org.sqlite.core.CoreStatement.internalClose(CoreStatement.java:109)
at org.sqlite.jdbc3.JDBC3Statement.close(JDBC3Statement.java:35)
at com.issam.iamcore.DatabaseConnection.close(DatabaseConnection.java:63)
at com.issam.iamcore.Main.main(Main.java:11)
Any help would be appreeciated, thanks !
You have successfully connected to the database, but did not create table Identity before executing insert query, as it says in the stack trace:
Connection to test.db successful
java.sql.SQLException: no such table: Identity
Call this before inserting a row:
String createQuery = "CREATE TABLE Identity (id INT PRIMARY KEY NOT NULL, name TEXT, email TEXT)";
statement.executeUpdate(createQuery);
Related
package com.example.financecontrol;
import java.sql.*;
public class DBController {
public static Connection Connector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:FinanceControl.sqlite");
return conn;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
}
Is there a way to initialise database with some data if it does not exist. The problem is that I want to add some tables and configs while launching the application for the first time?
What I needed is "CREATE TABLE IF NOT EXISTS" statement. It worked properly!
I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful
I'm having a problem, not sure how to fix:
connection code:
public class sqliteConnection {
Connection conn = null;
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:V:\\Database\\table.sqlite");
JOptionPane.showMessageDialog(null, "Conected to Database");
return conn;
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
and where I'm using this connection:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql="insert into test (test) value (?)";
PreparedStatement pst=conn.prepareStatement(sql);
pst.setString(1, Test.getText());
}catch (Exception e){
e.printStackTrace();
}
}
I'm getting a SQLITE_ERROR SQL error or missing database (near "value": syntax error) error, and I cant tell where the error could come from. I just created a test table in sqlite to test the connection, with one column which is a 'TEXT' named test. any help?
I have the following Java 7 code to create a CachedRowSet.
CachedRowSet crs = RowSetProvider.newFactory().createCachedRowSet();
Is there a way to get the Connection object from the CachedRowSet object? I would like to set autoCommit to false on the Connection object before invoking the acceptChanges() on CachedRowSet as I'm getting the following exception when invoking acceptChanges().
javax.sql.rowset.spi.SyncProviderException: Can't call commit when autocommit=true
There is a COMMIT_ON_ACCEPT_CHANGES field on CachedRowSet, but it's Deprecated.
Well, it took some time for me to reproduce the issue at my end. Setting the autoCommit value of the Connection to false via conn.setAutoCommit(false); resolved this issue.
Following is the sample working program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
public class CRSetChecker {
public static void main(String[] args) {
String connectString = "jdbc:oracle:thin:scott/tiger" +
"#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)" +
"(HOST=myorahost)(PORT=5521))" +
"(CONNECT_DATA=(SID=myorasid)))";
//Get DB connection
Connection conn = (new CRSet()).getConnection(connectString);
if (conn == null) {
System.out.println("Connection failed");
System.exit(0);
} else {
System.out.println("Connection established successfully!");
try {
CachedRowSet crs =
RowSetProvider.newFactory().createCachedRowSet();
String query="select ename from emp";
crs.setCommand(query);
crs.execute(conn);
//Set auto commit false
conn.setAutoCommit(false);
int count = 0;
while(crs.next()){
String name = crs.getString(1);
count++;
System.out.println(name);
if(count==1){
crs.updateString(1, "COOPER");
crs.updateRow();
crs.acceptChanges(conn);
System.out.println("After update:"+crs.getString(1));
}
}
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
public Connection getConnection(String connectString)
{
Connection con = null;
try {
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection(connectString);
} catch (SQLException ex) {
ex.printStackTrace();
}
return con;
}
}
I have a basic connection to an oracle database, I getting back the first two print statements i.e connecting to the database and reading back the query which is to be inserted but I'm not reaching line updateQuery = statement.executeUpdate(); and therefore the statement isn't executed.
I'm getting no error and I have the ojdbc driver downloaded, any suggestions ?
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
public class conn1 {
public static void main(String[] argv) {
//Scanner out = new Scanner(String);
//In Java, we use plain JDBC calls to insert a record in STUDENTS table. We use sequence STUDENT_SEQ to generate primary key.
//Once the record is inserted, we want the last inserted primary value.
PreparedStatement statement = null;
int updateQuery = 0;
String QUERY = "INSERT INTO SYS.STUDENTS (student_id, NAME, EMAIL, BIRTH_DATE)"
+ "VALUES ('1','Hermoine', 'Hermoine#hogwarts.edu', '08-Nov-1987')";
// load oracle driver
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// get database connection from connection string
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:attendanced", "louise", "Attend123!");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (connection != null) {
System.out.println("Successfullly connected to Oracle DB");
try {
statement = connection.prepareStatement(QUERY);
System.out.println("Insert This Query :" + QUERY);
updateQuery = statement.executeUpdate(); //Erroneous line.
if (updateQuery != 0) {
System.out.println("Record inserted successfully");
} else {
System.out.println("Error, Record not inserted");
}
} catch (SQLException e) {
e.printStackTrace();
}
} else {
System.out.println("Failed to connect to Oracle DB");
}
}
}