Why am I getting this error with the below code? - mariadb

Why am I getting this error. I don't know where am I going wrong.
String query = "update admin set adm_name = ? where adm_id = ?";
//ResultSet rs;
try {
DBConnection dbc = new DBConnection();
if(!dbc.connected) dbc.getConnection();
PreparedStatement st =
(dbc.con).prepareStatement(query);
st.setString(1, a.getAdm_name());
st.setString(2, a.getAdm_id());
st.executeUpdate(query);
st.close();
(dbc.con).close();
}
catch(Exception exc)
{
exc.printStackTrace();
}
Error:
java.sql.SQLSyntaxErrorException: You have an error in your SQL
syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near '? where adm_id = ?' at line
1
The query runs well in phpmyadmin.

Related

How to write transaction in Mariadb?

using query " BEGIN; INSERT INTO employee (id, name) VALUES (:id,:name); COMMIT ;" to commit the transaction through java code and additionally setting id and name parameters but getting below error.
"Caused by: java.sql.SQLSyntaxErrorException: (conn=812) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO employee (id, name) VALUES (150,'150_abc'); COMMIT' at line 1
have tried with belwo query:
start transaction; INSERT INTO employee (id, name) VALUES (:id,:name); COMMIT ;
using MariaDb version 10.7.3
you should try the following :
MOST IMPORTANT TO CONSIDER, IS TO SET THE AUTOCOMMIT TO FALSE, otherwise MariaDB will refuse not automatic transaction management.
import java.sql.*;
public class App {
public static void main(String[] argv) {
try (Connection conn = DriverManager.getConnection("jdbc:mariadb://192.0.2.1:3306?user=db_user&password=db_user_password")) {
conn.setAutoCommit(false);
try {
try (PreparedStatement prep = conn.prepareStatement("INSERT INTO test.accounts(first_name, last_name, email, amount) VALUES (?, ?, ?, ?)")) {
prep.setString(1, "John");
prep.setString(2, "Smith");
prep.setString(3, "john.smith#example.com");
prep.setDouble(4, 900.00);
prep.executeQuery();
}
try (PreparedStatement prep = conn.prepareStatement("UPDATE test.accounts SET amount = ? WHERE email = ?")) {
prep.setDouble(1, 1000.00);
prep.setString(2, "john.smith#example.com");
prep.executeQuery();
}
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
conn.rollback();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

How to check table is empty with count(*)

I am trying to check if a table is empty. I code this method:
public boolean checkIfNULL()
throws SQLException, ClassNotFoundException {
boolean flag=false;
System.out.println("Checking if table is empty...");
String sq = "select count(*) from TABLE1";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
PreparedStatement stm = c.prepareStatement(sq);
int rowsAffected = stm.executeUpdate();
if(rowsAffected == 0)
flag=true;
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (stm != null) {
stm.close();
}
if (c != null) {
c.close();
}
}
return flag;
}
but sth wrong is hapenning and I get an error message
Query returns results
Exceptionn: java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
How I check the returning value of check?
UPDATE 1:
Instead of the query above, I tried also SELECT EXISTS(SELECT 1 FROM TABLE1)
but the same is happening..
UPDATE 2:
I used this:
ResultSet rs = stm.executeQuery();
if(!rs.next())
flag=true;
else
System.err.println("ERROR - The table has records...");
and it prints the ERROR - "The table has records...". How is this possible? I see the table through SQLite manager and it is empty!
You are executing a SELECT, so you need to use executeQuery, not executeUpdate. executeUpdate is for statements like UPDATE, DELETE and INSERT, executeQuery is for executing statements that return a result set (like SELECT).
You need to execute a select statement, and do:
try (ResultSet rs = stm.executeQuery()) {
rs.next(); // You always have a row, with the count
int count = rs.getInt(1);
flag = count == 0;
}
The code in your update won't work, because if you do a SELECT count(*) FROM table, then you always have one row (with the count).

Blackberry sqlite - Cannot prepare already prepared statement exception

In blackberry sqlite while executing the below code i getting exception "Cannot prepare already prepared statement"
public Department[] getDepartment()
{
Department[] department = null;
try
{
database = DatabaseFactory.open(myURI);
Statement st = database.createStatement("SELECT code, name, status FROM Department");
st.prepare();
Cursor c = st.getCursor();
Row r;
int i = 0;
department = new Department[i];
while(c.next())
{
r = c.getRow();
i++;
Department dept = (Department) r.getObject(i);
department[i] = dept;
}
st.close();
database.close();
}
catch ( Exception e )
{
System.out.println("Exception occured --------------" +e.getMessage());
}
return department;
}
anybody know solution for this
The st.prepare() is only necessary if the statement is not prepared, which means:
The statement references an external variable
The statement references a computed variable
In this case, neither is the case, so the statement is redundant.
References
SQLite: File History - prepare.c
Getting “Re-preparing already prepared query” warning with caching enabled · Issue #581 · Netflix/astyanax · GitHub
SQLite: View Ticket - Repreparation errors are always returned as SQLITE_SCHEMA

Why (on a specific server) would ADO,NET get a Time Out exception after db result is returned and the reader is being closed?

I have some strange behavior occurring in an ASP.NET application that I am trying to fix.
I am getting the following error from code:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
I am familiar with this error and many of it's causes. All of my typical avenues of trouble shooting have failed.
Here are some of the dynamics:
The server was recently re-built. So it could be a server configuration issue.
This error only happens on a specific web server. When I run the application it locally, and from other servers it is fast. I cannot re-pro perf issues with the proc in MSSMS from my machine.
This tells me that it is specific to this server.
When I run The same proc using the OSql command--line utility It works. Fast.
This indicates that it is likely something .NET related, NOT db related
Prior to this code executing, I have executed other Stored procedures on this server, and on this same DB.
This suggests the proc may be related , but is not a "server X cannot talk to server Y"
I have gotten confirmation From DB owners that the DB has received the command, executed (>1second )it and returned the data.
By tracing the code, I see the results are returned and it is not until I try to close the data reader that the error occurs.
In fact I see it takes 36 milliseconds to execute the stored procedure and iterate through the result.
It looks like the call to DataReader.Close is what is taking time, and eventually timing out.
I have increased the max Pool from 31 to 100.
Here is a sample of what my code looks like, how it is structured. I have been hacking at it for trouble shooting: I have added the explict close to ensure I know where the error occurs. There may be syntax issues: I have made it generic, and may have introduced bugs in doing so.
public double GetMyData()
{
double returnValue;
// Used in logging to see if code was reached & how long it took.
System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
using (SqlConnection cn = Connections.GetSqlConnection())
{
cn.Open();
using (SqlCommand cmd = getSQLCommmand("SomeProcName"))
{
Log.Log.WriteTrace(string.Format("Execute {0} ","SomeProcName"),0);
s.Start();
SqlDataReader dr= null;
try
{
dr = cmd.ExecuteReader();
s.Stop();
Log.Log.WriteTrace("Timer", "ExecuteReader done " + s.ElapsedMilliseconds + "ms ", 0);
s.Start();
if (dr != null)
{
if (dr.Read())
{
returnValue =
Conversion.DBNullToDouble(
dr[0]);
}
s.Stop();
Log.Log.WriteTrace("Timer", "dr.read done (result:" + returnValue + ")" + s.ElapsedMilliseconds + "ms ", 0); // I get Here
}
}catch(Exception ex)
{
Log.Log.PersistException(ex);
}
//}
if(dr!=null && !dr.IsClosed)
dr.Close();// This times out
if (cn != null && cn.State !=ConnectionState.Closed)
cn.Close();
Log.Log.WriteTrace("DONE "),
;
}
}
return (returnValue);
}
UPDATE
dr.Close(); takes 2 minutes to execute. Just on this server. Locally it takes less than a second.
UPDATE
Per the accepted answer's comments: I have a proc that has multiple records. I am taking the fist one. Calling cmd.Cancel() has not fixed, but has drastically reduced the time taken to close the data reader. Exploring this should help me fix the problem. I do not know why this is only happening on this server, as the server is a dev server.
I see few problems in your code.
Try to use the Reader in a using statement it closes and disposes when finishing it.
You are closing 2 times the connection (when using
if (cn != null && cn.State !=ConnectionState.Closed)
cn.Close();
and in the using (SqlConnection cn = Connections.GetSqlConnection()) -- this one do it for you at the end of the statement
In your code you are not checking if the DataReader.HasRows So if your Sproc doesn't return a value it will throw an exception in the if (dr.Read()) so that could be the reason that's why you are getting sometimes the time out exception
If you only want to retrieve the value of the first column of the first row you should take a look to ExecuteScalar
Finally
I would rewrite your code like this (using DataReader)
public double GetMyData()
{
double returnValue;
// Used in logging to see if code was reached & how long it took.
System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
using (SqlConnection cn = Connections.GetSqlConnection())
{
cn.Open();
using (SqlCommand cmd = getSQLCommmand("SomeProcName"))
{
Log.Log.WriteTrace(string.Format("Execute {0} ","SomeProcName"),0);
s.Start();
using(SqlDataReader dr = cmd.ExecuteReader())
{
s.Stop();
Log.Log.WriteTrace("Timer", "ExecuteReader done " + s.ElapsedMilliseconds + "ms ", 0);
s.Start();
if (dr != null)
{
if(dr.HasRows)
{
if (dr.Read())
{
returnValue =
Conversion.DBNullToDouble(
dr[0]);
}
}
s.Stop();
Log.Log.WriteTrace("Timer", "dr.read done (result:" + returnValue + ")" + s.ElapsedMilliseconds + "ms ", 0); // I get Here
}
}
}
}
return (returnValue);
}
Or (with ExecuteScalar)
public double GetMyData()
{
double returnValue;
// Used in logging to see if code was reached & how long it took.
System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
using (SqlConnection cn = Connections.GetSqlConnection())
{
cn.Open();
using (SqlCommand cmd = getSQLCommmand("SomeProcName"))
{
Log.Log.WriteTrace(string.Format("Execute {0} ","SomeProcName"),0);
s.Start();
try
{
returnValue = Conversion.DBNullToDouble(cmd.ExecuteScalar());
s.Stop();
}
catch(Exception ex)
{
Log.Log.PersistException(ex);
}
}
}
return (returnValue);
}

SQL CE 3.5 problem with TableDirect table access

I try to insert hundreds of records into empty database table using TableDirect type of SqlCeCommand. The problem is I get an exception SqlCeException "Unspecified error" when calling SqlCeResultSet::Insert. Below is my code. Any hints?
Thanks
public bool StoreEventsDB2(List<DAO.Event> events)
{
try
{
SqlCeCommand command = new SqlCeCommand("Event");
command.CommandType = System.Data.CommandType.TableDirect;
SqlCeResultSet rs = _databaseManager.ExecuteResultSet(command, ResultSetOptions.Updatable | ResultSetOptions.Scrollable );
foreach (DAO.Event theEvent in events)
{
SqlCeUpdatableRecord record = rs.CreateRecord();
record.SetInt32( 0, theEvent.ID );
record.SetInt32( 1, theEvent.ParentID);
record.SetString(2, theEvent.Name);
record.SetDateTime(3, theEvent.DateTime);
record.SetDateTime(4, theEvent.LastSynced);
record.SetInt32(5, theEvent.LastSyncedTS);
record.SetString(6, theEvent.VenueName);
record.SetBoolean(7, theEvent.IsParentEvent);
record.SetDateTime(11, DateTime.Now);
rs.Insert(record);
}
}
catch (SqlCeException e)
{
Log.Logger.GetLogger().Log(Log.Logger.LogLevel.ERROR, "[EventManager::StoreEventsDB] error: {0}", e.Message);
return false;
}
catch (Exception e)
{
Log.Logger.GetLogger().Log(Log.Logger.LogLevel.ERROR, "[EventManager::StoreEventsDB] error: {0}", e.Message);
return false;
}
return true;
}
I am unsure how your connection is managed with the database manager which could be the culprit - make sure you are using one connection (sqlce doesn't play nice). Also the results set option "ResultSetOption.Scrollable" is not needed (at least I have never used it for an insert).
Below is the syntax I use when doing direct table inserts. Every database/data access object is wrapped in a using statement to dispose of objects after use - this is very important especially with the compact framework and sqlce as the garbage collection is less than ideal (you WILL get out of memory exceptions!). I have added a transaction to your code also so that the option is all or nothing.
Hope this helps:
using (var transaction = connection.BeginTransaction())
{
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandType = CommandType.TableDirect;
command.CommandText = "Event";
using (var rs = command.ExecuteResultSet(ResultSetOptions.Updatable))
{
var record = rs.CreateRecord();
foreach (DAO.Event theEvent in events)
{
record.SetInt32(0, theEvent.ID);
record.SetInt32(1, theEvent.ParentID);
record.SetString(2, theEvent.Name);
record.SetDateTime(3, theEvent.DateTime);
record.SetDateTime(4, theEvent.LastSynced);
record.SetInt32(5, theEvent.LastSyncedTS);
record.SetString(6, theEvent.VenueName);
record.SetBoolean(7, theEvent.IsParentEvent);
record.SetDateTime(11, DateTime.Now);
rs.Insert(record);
}
}
transaction.Commit();
}
}

Resources