sqlite java query does not insert into table - java

Have sqlite table named good_in with columns in_id, good_code, in_group, in_quantity, in_VATPaid
Here is my table example
and have method to insert records into it
public static void inputGoods(GoodsInput goodsinput){
String goodCode = goodsinput.getInGood().getGood_code();
int goodBatch = goodsinput.getInGroup();
int goodQuantity = goodsinput.getInQuantity();
double goodVATPaid = goodsinput.getInVatPaid();
String sqlInsert = "INSERT INTO good_in (good_code, in_group, in_quantity, in_VATPaid)"
+ " VALUES ('" + goodCode + "', " + "'" + goodBatch + "', " + "'" + goodQuantity
+ "', " + "'" +goodVATPaid + "');";
System.out.print(sqlInsert);
Connection conn = ConnectionFactory.ConnectDB();
try{
Statement statement = conn.createStatement();
statement.executeUpdate(sqlInsert);
}
catch(SQLException e){
}
}
Connection class
public static Connection ConnectDB(){
try{
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:kahuyq.db");
return con;
} catch (HeadlessException | ClassNotFoundException | SQLException ex){ JOptionPane.showMessageDialog(null, ex); }
return null;
}
When I copy the printed query to sqlite manager it adds the row, but from java it ends program with no error but does not add row to my table.
What is wrong?
Have also other method that checks weather the good_code exists in table good which have only 2 columns id and good_code and if does not exist adds it. this method is accessed from GoodsInput constructor. When I delete the method from constructor the other method works fine.
Here is that method
public static void insertGoods(Good g){
String sqlSelect = "Select * from good where good_code = '"
+ g.getGood_code() + "'" ;
String sqlInsert = "INSERT INTO good (good_code)"
+ "VALUES ('" + g.getGood_code() +"')";
Connection conn = ConnectionFactory.ConnectDB();
try{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sqlSelect);
while(!rs.next()){
statement.executeUpdate(sqlInsert);
break;
}
}
catch(SQLException e){
}
}

Try to add
conn.commit();
after the execution of your statement.

Related

Java Embedded, after insert I cannot recheck if the row exists

I am inserting a row in Java Derby Embedded database. Immediately I am rechecking whether the row with the particular ID exists. The code I use works fine elsewhere in Sqlite3, MySql etc. But in Derby it throws an error, invalid cursor state, no current row.( But the row is added and exists) What is that I am doing wrong?
String sql="";
stmt = conn.createStatement();
sql = "INSERT INTO USERLIST (UserID,UserName,PaWord,RealName) " +
"VALUES (" + Nextam + ",'" + f1 + "','" + f2 + "','" + f3 + "')";
stmt.executeUpdate(sql);
stmt.close();
Thread.sleep(1000);
// rechecking
stmt = conn.createStatement();
rs = stmt.executeQuery( "SELECT * FROM USERLIST where UserID=" + Nextam + "" );
String nameR = rs.getString("RealName");
if(nameR.length() < 2){
System.out.println( "Seems like Error " + Nextam );
}else{
String infum=nameR + " Added as " + Nextam;
ShowLab(infum);
}
stmt.close();
conn.close();
You didn't call rs.next() after you performed the stmt.executeQuery() call.
Are you sure this code works on other systems?

Error-com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'BY'

private void UptadeSupplierActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
Class.forName(driver);
Connection con = DriverManager.getConnection(url, user, pass);
Statement st = con.createStatement();
ResultSet rec =st.executeQuery("SELECT SupName, SupSurName" +
"FROM Suppliers" +
"ORDER BY SupName");
while(rec.next())
{
System.out.println(rec.getString("SupName") + "," + rec.getString("SupSurName") + ".");
}
st.close();
}
catch(Exception e)
{
System.out.println("Error-" + e.toString());
}
}
You concatenate your strings like this:
"SELECT SupName, SupSurName" + "FROM SUPPLIERS"
This will result into:
SELECT SupName, SupSurNameFROM Suppiers
Note that you are missing a space between "SupSurName" and "FROM". Either add a " " (space) between your strings or simply add a space to the end of each string.

How to pass variables into SQLite in java

I'm trying to create a SQLite for my game, and its working fine until I try to put some variables in the table HighScores.
If I try to put a variable it only works if I delete the "NOT NULL".
public void SQLite(){
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
stmt = c.createStatement();
String sql = "CREATE TABLE HighScores " +
"(ID INT PRIMARY KEY NOT NULL," +
" POINTS INT NOT NULL, " +
" NAME CHAR(50) NOT NULL, " +
" TIME INT NOT NULL, " +
" LEVEL INT NOT NULL)";
stmt.executeUpdate(sql);
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql2 = "INSERT INTO HIGHSCORES (ID,POINTS,NAME,TIME,LEVEL) " +
"VALUES (1, ?, 'rodrigo', 99, 1 );";
PreparedStatement ps = c.prepareStatement(sql2);
ps.setInt(1, 5);
stmt.executeUpdate(sql2);
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
}
Opened database successfully.
java.sql.SQLException: NOT NULL constraint failed: HighScores.POINTS
You are calling executeUpdate on stmt instead of the prepared statement. Since sql2 does not have any value for POINTS, it try to insert null hence the exception.
Change :
stmt.executeUpdate(sql2);
to
ps.executeUpdate();

Java SQLite database, insert entry giving nullPointerException

I am trying to create a generic method that can add an entry into a SQLite database, using Eclipse and Java.
When the table name is hardcoded it works fine, but when I try to pass in the table name as a string it is giving me a nullPointerException.
below is the method that creates that table:
public static void Table()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS COMPANY " +
"(ID INT PRIMARY KEY NOT NULL," +
" NAME TEXT NOT NULL, " +
" AGE INT NOT NULL, " +
" ADDRESS TEXT, " +
" SALARY REAL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Table created successfully");
}
and here is the method that inserts an entry into the created table. I want to pass in the table name through the method rather than hard coding it:
public static void Insert(String table, int id, String name, int age, String address, String salary)
{
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query="INSERT INTO "+table+" (ID,NAME,AGE,ADDRESS,SALARY) VALUES (?,?,?,?,?)";
PreparedStatement stmt = c.prepareStatement(query);
pstmt.setInt(1,id);
pstmt.setString(2,name);
pstmt.setInt(3, age);
pstmt.setString(4, address);
pstmt.setString(5, salary);
pstmt.executeUpdate();
pstmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
}
You have small mistake
just you have created two different PreparedStatement object
So change
PreparedStatement stmt = c.prepareStatement(query);
to
pstmt = c.prepareStatement(query);

java.sql.SQLException: lock wait time out exceeded; try restarting transaction

Hi in my project i am have created 2 tables which was Role_header and Role_details tables.
And also Role_details table is referring to the Role_header table.
In my java class i have two method they are
insertRoleHeader(...) --> which will be called first and set conn.setAutoCommit(false).i didn't commit this because following this i want to insert role_details with multiple records in Role_details table. so i will call this method first, if any exceptions thrown. i have set this to rollback in catch.
insertRoleDetails(.....) --> this method will be called by forloop. each and every calling of this method i will commit. at that time i am getting error as java.sql.SQLException: lock wait time out exceeded; try restarting transaction.
my sample code is here:
public void insertHeader(RoleMasterSupport rMS) throws SQLException {
connectDB();
Statement stmt = null;
try {
roleMasterConn.setAutoCommit(false);
stmt = roleMasterConn.createStatement();
String sql = "insert into role_header( create_user, " +
"create_date, " +
"run_user, " +
"run_date, " +
"role_id, " +
"role_name, "+
"remarks) " +
"values('"+Constants.sUserName+"', now(), "
+ "'"+Constants.sUserName+"', now(), "
+ "'"+rMS.getsRoleID()+"', '"+rMS.getsRoleName()+"', "
+ "'"+rMS.getsRemarks()+"') ";
stmt.executeUpdate(sql);
stmt.close();
} catch (SQLException e) {
roleMasterConn.rollback();
throw e;
}
}
public void insertDetails(RoleMasterSupport rMS, TableModel model) throws SQLException
{
for (int i = 0; i < model.getRowCount(); i++) {
dbop.insertDetail(rMS, rMS.getaLScreenNames().get(i),
rMS.getaLAdd().get(i), rMS.getaLView().get(i),
rMS.getaLModify().get(i), rMS.getaLDelete().get(i));
}
}
public void insertDetail(RoleMasterSupport rMS, String sScreenName, String sAdd, String sView, String sModify, String sDelete) throws SQLException
{
connectDB();
Statement stmt = null;
try {
roleMasterConn.setAutoCommit(false);
stmt = roleMasterConn.createStatement();
String sql = "insert into role_details( create_user, " +
"create_date, " +
"run_user, " +
"run_date, " +
"role_id, " +
"screen_name, " +
"modify_screen, " +
"add_screen, " +
"delete_screen, " +
"view_screen) " +
"values('"+Constants.sUserName+"', now(), "
+ "'"+Constants.sUserName+"', now(), "
+ "'"+rMS.getsRoleID()+"', '"+sScreenName+"', "
+ "'"+sModify+"', '"+sAdd+"', "
+ "'"+sDelete+"', '"+sView+"') ";
stmt.executeUpdate(sql);
roleMasterConn.commit();
} catch (SQLException e) {
roleMasterConn.rollback();
throw e;
}
}

Categories

Resources