public synchronized void saveMatchValue(int photoRecOwner,
int[] photoRecAssign, float[] value) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.beginTransaction();
String sql = " UPDATE " + TypeContract.CTablePhotoMatch.TABLE_NAME
+ " SET " + TypeContract.CTablePhotoMatch.VALUE + "=? "
+ " WHERE " + TypeContract.CTablePhotoMatch.FK_OWNER
+ "=? AND " + TypeContract.CTablePhotoMatch.FK_ASSIGN + "=? ;"
+ " INSERT OR IGNORE INTO "
+ TypeContract.CTablePhotoMatch.TABLE_NAME + "("
+ TypeContract.CTablePhotoMatch.FK_OWNER + ","
+ TypeContract.CTablePhotoMatch.FK_ASSIGN + ","
+ TypeContract.CTablePhotoMatch.VALUE + ") VALUES (?, ?, ?);";
SQLiteStatement stmt = database.compileStatement(sql);
try {
int rows = photoRecAssign.length;
for (int i = 0; i < rows; i++) {
if (photoRecOwner > photoRecAssign[i]) {
stmt.bindLong(1, photoRecOwner);
// stmt.bindLong(index, value)
stmt.bindLong(2, photoRecAssign[i]);
} else {
stmt.bindLong(1, photoRecAssign[i]);
stmt.bindLong(2, photoRecOwner);
}
stmt.bindDouble(3, value[i]);
stmt.execute();
stmt.clearBindings();
}
database.setTransactionSuccessful();
} finally {
stmt.close();
// updtStmt.close();
database.endTransaction();
// database.close();
}
}
Without error and compile-error,
I dont know if the sql statement syntax is correct: concrete the : ; , but without compile errors, the insert and(probably update) command are not executed....
Can I catch some more details?(Of sqlite statemenst) to find out the bug
You can only use SQLiteStatement to execute single statements. The SQL after the ; is not executed.
Split the SQL to execute the statements separately.
Related
I want to move to the other frame if the query result is empty. How can I check if the query is empty?
String query2 ="Select* from biletbilgileri where FilminÄ°smi='" + filmKoltuk + "'" +
" " + "and" + " " + "SeansTarihi='" + SeansTarihKoltuk + "'" + " " + "and" + " " +
"SeansSaati='" + SeansSaatKoltuk + "'";
Statement stmt1=conn.createStatement();
ResultSet rs1=stmt1.executeQuery(query2);
rs1.next();
if(rs1==null)
{
tesekkurEkrani1.setVisible(true);
tesekkurEkrani1.setSize(1000,500); }
else {
JOptionPane.showMessageDialog(null, "This chair isn't empty!");
}
You want to use SQL count(*) in the query select count(*) from biletbilgileri .... If the returned value is 0, there are no rows returned by your original query.
String query2 = "select count(*) from biletbilgileri ...";
ResultSet rs1 = stmt1.executeQuery(query2);
rs1.next();
int count = rs1.getInt(1);
if (count == 0) {
// empty
}
When you call rs1.next();, it returns a boolean. If the boolean is false, it means there are no more rows. so I think you want to do this:
boolean notEmpty = rs1.next();
if(notEmpty )
{
I'm using sql developer and netbeans when ever i try to insert data into the table this error "sql Command has not properly ended".
This is what i tried.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
dbconnection db = new dbconnection();
try {
db.connect();
db.stm = db.con.createStatement();
int result = db.stm.executeUpdate(
"insert into payment values'" + txt_paymentid.getText() + "','" + txt_reservation.getText() +"',
" + "'"+txt_fname.getText()+"',
'"+txt_lname.getText()+"' ,'"+txt_roomid.getText()+"' ,'"+txt_rate.getText()+"' ," + " '"+((JTextField)txt_datein.getDateEditor().getUiComponent()).getText()+"' ,"
+ "'"
((JTextField
)txt_dateout.getDateEditor().getUiComponent()).getText() + "'," + "'" + txt_days.getText() + "','" + txt_payment.getText() + "','" + txt_balance.getText() + "'"
);
if (result > 0) {
JOptionPane.showMessageDialog(this, "Data has been saved succesfully");
} else {
JOptionPane.showMessageDialog(this, "no data has been saved");
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}
For a start
The sql should be in the ()
executeUpdate()("insert...
->
executeUpdate("insert...)
second it looks like the insert command itself it not valid
insert into table values (' ....
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;
}
}
i added sqlite-jdbc-3.7.2.jar to build path. I used insert query. when i opened the wellec.db with notepad, i can see records. But my select is not working.
HERE WellInfo class properties
public Integer wellID;
public Integer measurement;
public String wellname;
public Integer wellstatus;
public String licenseno;
public String gl;
public String kb;
public String spuddate;
public String drillingenddate;
public String totaldepth;
public String notes;
public String easting;
public String northing;
public String coordinatesystem;
public Integer islogadd;
here is my createtable sql
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS WELLINFO " +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ," +
" WELLNAME CHAR(90) NOT NULL, " +
" WELLSTATUS INT NOT NULL," +
" MEASUREMENT INT NOT NULL," +
" ISLOGADD INT NOT NULL," +
" GL CHAR(50) NOT NULL, " +
" KB CHAR(50) NOT NULL, " +
" SPUDDATE CHAR(50) NOT NULL, " +
" TOTALDEPTH CHAR(50) NOT NULL, " +
" LICENSENO CHAR(50) NOT NULL, " +
" DRILLINGENDDATE CHAR(50) NOT NULL, " +
" NOTES CHAR(150) NOT NULL, " +
" EASTING CHAR(50) NOT NULL, " +
" NORTHING CHAR(50) NOT NULL, " +
" COORDINATESYSTEM CHAR(50) NOT NULL)";
stmt.executeUpdate(sql);
...//other tables sql and stmt.executeUpdate(sql)
stmt.close();
c.commit();
here is my insert query which is working. WellInfo wi as parameter
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO WELLINFO " +
"(ID, WELLNAME, WELLSTATUS , MEASUREMENT, ISLOGADD , GL, KB, SPUDDATE, TOTALDEPTH, " +
"LICENSENO , DRILLINGENDDATE, NOTES, EASTING, NORTHING, COORDINATESYSTEM) " +
"VALUES (NULL,'" + wi.wellname + "'," + wi.wellstatus + "," + wi.measurement + "," +
"" + wi.islogadd +",'" + wi.gl + "','" + wi.kb + "','" + wi.spuddate + "'," +
"'" + wi.totaldepth + "','" + wi.licenseno + "','" + wi.drillingenddate + "', " +
"'" + wi.notes + "','" + wi.easting + "','" + wi.northing + "','" + wi.coordinatesystem + "');";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
return 0;
here is my select
Connection c = null;
Statement stmt = null;
WellInfo[] wi = new WellInfo[60000];
WellInfo[] wi2 = new WellInfo[0];
int i = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
//c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("select * from WELLINFO");
//c.commit();
//if(rs.getRow() > 0)
while ( rs.next() ) { //HERE IS THE PROBLEM
wi[i].wellID = rs.getInt("ID");
i++;
}
wi2 = new WellInfo[i];
for(int j = 0; j < i - 1; j++){
wi2[j] = wi[j];
}
rs.close();
stmt.close();
return wi2;
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
return wi2;
Sorry not specify the problem. Here it is:
SELECT QUERY problem when i call rs.next(), i got the error java.lang.NullPointerException.
wi[i] is null => you can't call wi[i].wellID before you instantiate wi[i], you should do something like
wi[i] = new WellInfo() then call wi[i].wellID
I am trying to insert records into SQL Server using jdbc conn (in java).
I am able to insert into SQL, if I manually copy the query statement in the java file. But its not inserting from the code?
Please help, where am I committing mistake?
PreparedStatement preparedStatement = null;
if (conn != null) {
System.out.println("Connection Successful!");
}
//Create a Statement object
Statement sql_stmt = conn.createStatement();
//Create a Statement object
Statement sql_stmt_1 = conn.createStatement();
//Result Set for Prouduct Table
ResultSet rs = sql_stmt.executeQuery("SELECT MAX(ID), MAX(RG_ID), MAX(WG_ID) FROM " + strDBName + ".[dbo].Product");
if ( rs.next() ) {
// Retrieve the auto generated key(s).
intID = rs.getInt(1);
intRG_ID = rs.getInt(2);
intWG_ID = rs.getInt(3);
}
for (int iCount = 0 ;iCount < arrListLevel_1_Unique.size(); iCount++)
{
//Result Set for Prouduct Table
sql_stmt_1.executeUpdate("\n IF NOT EXISTS(SELECT 1 FROM " + strDBName + ".[dbo].Product WHERE [Name] NOT LIKE '" + arrListLevel_1_Unique.get(iCount) + "') "
+ "\nINSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
+ "[RG_ID],[WG_ID],[Parent_Product]) "
+ "VALUES ( '" + arrListLevel_1_Unique.get(iCount) + "',"
+ + (intWG_ID + intRowIncrement) + ", " + (intWG_ID + intRowIncrement + 1) + ", 5828)");
intRowIncrement++ ;
}
rs.close();
sql_stmt.close();
sql_stmt_1.close();
//Close the database connection
conn.close();
You have two plus signs + in the fifth row:
+ + (intWG_ID + intRowIncrement) + ...
Otherwise, the problem may lie in the IF ... statement. You can try this instead:
sql_stmt_1.executeUpdate(
" INSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
+ "[RG_ID],[WG_ID],[Parent_Product]) "
+ " SELECT '" + arrListLevel_1_Unique.get(iCount) + "',"
+ (intWG_ID + intRowIncrement) + ", "
+ (intWG_ID + intRowIncrement + 1) + ", 5828 "
+ " WHERE NOT EXISTS( SELECT 1 FROM " + strDBName
+ ".[dbo].Product WHERE [Name] LIKE '"
+ arrListLevel_1_Unique.get(iCount) + "') "
) ;
I think the problem lies on the "\n", have you tried eliminating those 2 of "\n" and see if it's working?
Actually this kind of implementation (building SQL string with string concatenation) is really bad. At first is prone to SQL injection, and then secondly you will have problem if the value to be inserted contains character single quote or ampersand.
Instead, you should use "prepare statement".
And it's tidier to store the SQL string into a variable before executing it. So that you can log it (for debug purpose), roughly something like this:
String sqlCommand = "select * from " + tableName;
System.out.println(sqlCommand);
sqlStatement.executeUpdate(sqlCommand);
P.S. it is not advised to use system.out.println for debug, you should implement a proper logging system.