I am using MySQL Workbench in and Netbeans for my Java project.
While inserting data into the database, it is showing the error:
; Expected Not a statement
Here is the Java code:
public int adduser(String fname,String mname,String lname,String address,
String phone,String email,String designation,
String subject,String institute,String inemail,
String uname,String pwd,String utype)
{
int n=0;
try{
String sql=
"insert into user(user_name,password,type,specialize,f_name,m_name, " +
"l_name, address,phone,email,designation,institute,in_email) " +
"values('"+uname+"','"+pwd+"','"+utype+"','"+subject+"'," +
"'"fname"','"mname"','"lname"','"address"','"phone"','"email"','"designation"','"institute"','"inemail"')";
n = db.modifyingQueries(sql);
}
catch(Exception e)
{
}
return n;
}
What does this error mean? What is wrong with my SQL statement?
You have missed the concatenation of the string by + sign.
String sql="insert into user(user_name,password,type,specialize,f_name,m_name,l_name,"
+ "address,phone,email,designation,institute,in_email)values('"+uname+"','"+pwd+"','"+utype+"','"+subject+"',"
+ "'"+fname+"','"+mname+"','"+lname+"','"+address+"','"+phone+"','"+email+"','"+designation+"','"+institute+"','"+inemail+"')";
Related
I have written this code to insert json data in to sqlite in android its working fine but i have 50000+ row to insert so its taking so much time to insert into sqlite database. So how can I insert this data in fastest way please kindly give me the code I am very new in android. thank in advance.
Below i have written my code to insert data
private void insertItemDetails() {
final ProgressDialog loading = ProgressDialog .show(this,"Updating Data From Tally","Please wait");
StringRequest stringRequest=new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
loading.show();
itemDatabaseCon.open();
itemDatabaseCon.delete();
itemDatabaseCon.close();
itemDatabaseCon.open();
itemDatabaseCon.createTable();
int a=response.length();
// boolean b=a.equalsIgnoreCase("no");
Log.d("value", String.valueOf(a));
if (a==2) {
Log.d("inside item if loop ",response);
}
else {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("posts");
for (int i = 0; i < array.length(); i++) {
JSONObject ob = array.getJSONObject(i);
String stockid = ob.getString("stockid");
String itemname = ob.getString("itemname");
String group = ob.getString("group");
String baseunit = ob.getString("baseunit");
String alternateunit = ob.getString("alternateunit");
String gst = ob.getString("gst");
String hsn = ob.getString("hsn");
String mrp = ob.getString("mrp");
String sdtsellrate = ob.getString("sdtsellrate");
String closingstock = ob.getString("closingstock");
ContentValues contentValues = new ContentValues();
contentValues.put(Constant2.key_itemstockid, stockid);
contentValues.put(Constant2.key_itemname, itemname);
contentValues.put(Constant2.key_itemgroup, group);
contentValues.put(Constant2.key_itembaseunit, baseunit);
contentValues.put(Constant2.key_itemalternateunit, alternateunit);
contentValues.put(Constant2.key_itemgst, gst);
contentValues.put(Constant2.key_itemhsn, hsn);
contentValues.put(Constant2.key_itemmrp, mrp);
contentValues.put(Constant2.key_itemsdtsellrate, sdtsellrate);
contentValues.put(Constant2.key_itemclosingstock, closingstock);
itemDatabaseCon.insert(Constant2.Table_name, contentValues);
}
}
loading.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("got api error ffff" , error.getMessage());
}
});
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Here is my database controller code.
public class ItemDatabaseCon {
String TAG = "DBAdapter";
private SQLiteDatabase db;
private ItemDatabaseCon.DBHelper dbHelper;
public ItemDatabaseCon (Context context) {
dbHelper = new ItemDatabaseCon.DBHelper(context);
}
public void open() {
if (null == db || !db.isOpen()) {
try {
db = dbHelper.getWritableDatabase();
} catch (SQLiteException sqLiteException) {
}
}
}
public void close() {
if (db != null) {
db.close();
}
}
public int insert(String table, ContentValues values) {
try {
db = dbHelper.getWritableDatabase();
int y = (int) db.insert(table, null, values);
db.close();
Log.e("Data Inserted", "Item Data Inserted");
Log.e("number of row", y + "");
return y;
} catch (Exception ex) {
Log.e("Error Insert", ex.getMessage().toString());
return 0;
}
}
public void delete() {
db.execSQL("DROP TABLE IF EXISTS " + Constant2.Table_name);
}
public int getCount()
{
db = dbHelper.getWritableDatabase();
String qry="SELECT * FROM "+Constant2.Table_name;
Cursor cursor=db.rawQuery(qry,null);
return cursor.getCount();
}
public void createTable()
{
String create_sql = "CREATE TABLE IF NOT EXISTS " + Constant2.Table_name + "("
+ Constant2.key_id + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Constant2.key_itemstockid + " TEXT ," + Constant2.key_itemname + " TEXT ," + Constant2.key_itemgroup + " TEXT ,"
+ Constant2.key_itembaseunit + " TEXT ,"+ Constant2.key_itemalternateunit + " TEXT ,"+ Constant2.key_itemgst + " TEXT ,"
+ Constant2.key_itemhsn + " TEXT ,"+ Constant2.key_itemmrp + " TEXT ,"+ Constant2.key_itemsdtsellrate + " TEXT ,"
+ Constant2.key_itemclosingstock + " TEXT " + ")";
db.execSQL(create_sql);
}
public Cursor getAllRow(String table) {
return db.query(table, null, null, null, null, null, Constant2.key_id);
}
private class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, Constant2.DB_Name, null, Constant2.Db_Version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String create_sql = "CREATE TABLE IF NOT EXISTS " + Constant2.Table_name + "("
+ Constant2.key_id + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Constant2.key_itemstockid + " TEXT ," + Constant2.key_itemname + " TEXT ," + Constant2.key_itemgroup + " TEXT ,"
+ Constant2.key_itembaseunit + " TEXT ,"+ Constant2.key_itemalternateunit + " TEXT ,"+ Constant2.key_itemgst + " TEXT ,"
+ Constant2.key_itemhsn + " TEXT ,"+ Constant2.key_itemmrp + " TEXT ,"+ Constant2.key_itemsdtsellrate + " TEXT ,"
+ Constant2.key_itemclosingstock + " TEXT " + ")";
db.execSQL(create_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Constant2.Table_name);
}
}
}
You could do the inserts inside a single SQLite transaction. This would significantly reduce the disk writes from 50000+ to very few.
That is before the loops starts begin a transaction using the SQLiteDatabase's beginTransaction() method.
After the loop has completed (all rows have been inserted) successfully use the setTransactionSuccessful() method followed by the endTransactionMethod()
Note if you do not setTransactionSuccessful then the changes would be rolled back (so if you encounter an issue/error and want the changes (inserts) to not be applied use appropriate logic so that the setTransactionSuccessful is skipped but that the endTransaction is run)
e.g. The following might be suitable:-
....
else {
itemDatabaseCon.beginTransaction(); //<<<<<<<<<< ADDDED start the transaction
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("posts");
for (int i = 0; i < array.length(); i++) {
JSONObject ob = array.getJSONObject(i);
String stockid = ob.getString("stockid");
String itemname = ob.getString("itemname");
String group = ob.getString("group");
String baseunit = ob.getString("baseunit");
String alternateunit = ob.getString("alternateunit");
String gst = ob.getString("gst");
String hsn = ob.getString("hsn");
String mrp = ob.getString("mrp");
String sdtsellrate = ob.getString("sdtsellrate");
String closingstock = ob.getString("closingstock");
ContentValues contentValues = new ContentValues();
contentValues.put(Constant2.key_itemstockid, stockid);
contentValues.put(Constant2.key_itemname, itemname);
contentValues.put(Constant2.key_itemgroup, group);
contentValues.put(Constant2.key_itembaseunit, baseunit);
contentValues.put(Constant2.key_itemalternateunit, alternateunit);
contentValues.put(Constant2.key_itemgst, gst);
contentValues.put(Constant2.key_itemhsn, hsn);
contentValues.put(Constant2.key_itemmrp, mrp);
contentValues.put(Constant2.key_itemsdtsellrate, sdtsellrate);
contentValues.put(Constant2.key_itemclosingstock, closingstock);
itemDatabaseCon.insert(Constant2.Table_name, contentValues);
}
itemDatabaseCon.setTransactionSuccessful(); //<<<<<<<<<< ADDED indicate that changes (inserts) are all good
itemDatabaseCon.endTransaction(); //<<<<<<<<<< ADDED end the transaction
}
loading.dismiss();
....
//<<<<<<<<<< indicates the changed/added code
Edit
However, considering the insert method the above will have no affect as you are closing the database after an insert. Closing the database and then re-opening it is very costly resource wise.
As such to benefit from running all the inserts in a single transaction you could use :-
public int insert(String table, ContentValues values) {
try {
db = dbHelper.getWritableDatabase();
int y = (int) db.insert(table, null, values);
//db.close(); //<<<<<<<<<< Commented out so as to not close the database
Log.e("Data Inserted", "Item Data Inserted");
Log.e("number of row", y + "");
return y;
} catch (Exception ex) {
Log.e("Error Insert", ex.getMessage().toString());
return 0;
}
}
I'm trying to implement a program to add a Binary.
The code that is displayed results in run time error.
class Solution {
public String addBinary(String a, String b)
{
return Integer.toBinaryString(Integer.parseInt(a, 2) + Integer.parseInt(b, 2));
}
}
The error:
Runtime Error Message:
Line 5: java.lang.NumberFormatException: For input string: "10100000100100110110010000010101111011011001
Input :a = "11", b = "1"
Output: "100"
Tell me if the code bellow can help you. It works here
public class Main
{
public static void main(String[] args) {
addBinary("11", "1");
}
public static void addBinary(String a, String b)
{
int value1 = Integer.parseInt(a,2);
int value2 = Integer.parseInt(b,2);
System.out.println("String to int: "+ value1 + " " + value2);
String binary1 = Integer.toBinaryString(value1);
String binary2 = Integer.toBinaryString(value2);
System.out.println("Your input in binary: "+ binary1 + " " + binary2);
}
}
So basically I want this test to pass should a valid name , like Paul, be entered. However, the junit always fails and I just cant figure out why. Any help is greatly appreciated. The code actually works when I run it also.
public int searchCustomer(String fName) throws SQLException
{
displayAllCustomers();
if(fName.isEmpty())
{
System.out.println("Please enter a name to search: ");
Scanner scanner = new Scanner(System.in);
fName = scanner.nextLine();
}
String fnameQ="Select * from customers where first_name='"+fName+"';";
try
{
rs = stmt.executeQuery(fnameQ);
while (rs.next())
{
int cus_id = rs.getInt("cus_id");
int reg_id=rs.getInt("reg_id");
String first_name = rs.getString("first_name");
String last_name = rs.getString("last_name");
int dob=rs.getInt("dob");
String address_line1=rs.getString("address_line1");
String address_line2=rs.getString("address_line2");
String eircode=rs.getString("eircode");
System.out.println("" + cus_id + " ¦ " + reg_id + " ¦ " + first_name + " ¦ " + last_name + " ¦ " + dob+ " ¦ " + address_line1 + " ¦ " + address_line2 + " ¦ " + eircode);
}
}
catch (SQLException sqle)
{
System.out.println("Error: failed to display all products.");
System.out.println(sqle.getMessage());
System.out.println(fnameQ);
return 0;
}
return 1;
}
Here is the junit test.
public void testsearchCustomer0001() throws SQLException {
newsagentDatabase testObject = new newsagentDatabase();
try{
assertEquals(1,testObject.searchCustomer("Paul"));
}
catch(Exception e)
{
fail("This should be true");
}
}
I am using junit3 if that is needed info. The actual aim of the code is to output info from a database. If you have any questions ask them!!! I will be actively checking here.
a friend and I are trying to write a program in Processing. The program needs to be able to connect to our MySQL database pull information at random and display it. we have gotten that much to work. with the following code
import de.bezier.data.sql.*;
MySQL dbconnection;
void setup()
{
size( 100, 100 );
String user = "username";
String pass = "password";
// name of the database to use
String database = "databasename";
// name of the table that will be created
//
String table = "tablename";
//
dbconnection = new MySQL( this, "ip", database, user, pass );
if ( dbconnection.connect() )
{
// now read it back out
//
dbconnection.query( "SELECT COUNT(id) FROM quiz_table" );
dbconnection.next();
int NumberOfRows = dbconnection.getInt(1);
float random = random(1, NumberOfRows);
int roundrandom = round(random);
println(" Row Number: " + roundrandom );
dbconnection.query( "SELECT * FROM quiz_table WHERE id =" + roundrandom);
while (dbconnection.next())
{
int n = dbconnection.getInt("id");
String a = dbconnection.getString("name");
String c = dbconnection.getString("charactor");
String m = dbconnection.getString("game");
int y = dbconnection.getInt("year");
String q= dbconnection.getString("quote");
println(n + " " + a + " " + c + " " + m + " " + y + " " + q);
}
}
else
{
// connection failed !
}
}
void draw()
{
// i know this is not really a visual sketch ...
}
this seems to work fine. however we plan to make the program preform many more tasks and to keep things more manageable we wanted to make somethings objects in this case i want to make an object that will connect to the database when its called. The following is what i have come up with but despite reworking several ways I can't quite get it to work.
import de.bezier.data.sql.*;
MySQL dbconnection;
connect1 myCon;
void setup()
{
size(300,300);
myCon = new connect1("username","password","database","table");
myCon.dbconnect();
}
void draw()
{
}
class connect1 {
String user;
String pass;
String data;
String table;
connect1(String tempuser, String temppass, String tempdata, String temptable) {
user = tempuser;
pass = temppass;
data = tempdata;
table = temptable;
}
void dbconnect(){
dbconnection = new MySQL( this, "ip", data, user, pass );
if ( dbconnection.connect() )
{
// now read it back out
dbconnection.query( "SELECT COUNT(id) FROM table" );
dbconnection.next();
int NumberOfRows = dbconnection.getInt(1);
float random = random(1, NumberOfRows);
int roundrandom = round(random);
println(" Row Number: " + roundrandom );
dbconnection.query( "SELECT * FROM table WHERE id =" + roundrandom);
while (dbconnection.next())
{
int n = dbconnection.getInt("id");
String a = dbconnection.getString("name");
String c = dbconnection.getString("charactor");
String m = dbconnection.getString("game");
int y = dbconnection.getInt("year");
String q= dbconnection.getString("quote");
println(n + " " + a + " " + c + " " + m + " " + y + " " + q);
}
}
else
{
println("fail");
}
}
//end of class
}
Sorry if that is at all hard to understand
The constructor of MySQL expects a PApplet as the first argument. When you call new MySQL(this inside your object, this does no longer refer to the main PApplet as it did in your first program.
The simplest way to fix this might be:
myCon.dbconnect(this); // send the PApplet as argument
...
void dbconnect(PApplet parent) {
dbconnection = new MySQL( parent, "ip", data, user, pass );
...
Another option would be to pass the PApplet to the constructor of your object, storing it in a property, and using that property when calling new MySQL.
Hi i was using stored procedure in SQL Server to pass parameters to the query ,
but now I'm changing my database to ms access and it's my first time to deal with.
how can i pass byte[] to sql query ?
bacause i got this error
Syntax error (missing operator) in query expression 'System.Byte[]'.
this is my code
public static int EditWhois(object ID,object Image, object Ranswer, object Fanswer1, object Fanswer2, object Fanswer3)
{
int result = 0;
String sql = "UPDATE Whois SET [Image]="+#Image+", Ranswer=" + Ranswer + ", Fanswer1=" + Fanswer1 + ",Fanswer2=" + Fanswer2 + ",Fanswer3=" + Fanswer3 + " WHERE ID=" + ID;
System.Windows.Forms.MessageBox.Show(sql);
cmd = new OleDbCommand(sql, con);
//cmd.Parameters.AddWithValue("#ID", ID);
//cmd.Parameters.AddWithValue("#Image", Image);
//cmd.Parameters.AddWithValue("#Ranswer", Ranswer);
//cmd.Parameters.AddWithValue("#Fanswer1", Fanswer1);
//cmd.Parameters.AddWithValue("#Fanswer2", Fanswer2);
//cmd.Parameters.AddWithValue("#Fanswer3", Fanswer3);
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
return result;
}
Use # parameter substitution. Also as #BoltClock says, change you method signature.
public static int EditWhois(object ID,object Image, object Ranswer,
object Fanswer1, object Fanswer2, object Fanswer3)
{
int result = 0;
String sql = "UPDATE Whois SET [Image]=#Image, Ranswer=#Ranswer, " +
"Fanswer1=#Fanswer1, Fanswer2=#Fanswer2, Fanswer3=#Fanswer3 " +
"WHERE ID=#ID";
cmd = new OleDbCommand(sql, con);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Image", Image);
cmd.Parameters.AddWithValue("#Ranswer", Ranswer);
cmd.Parameters.AddWithValue("#Fanswer1", Fanswer1);
cmd.Parameters.AddWithValue("#Fanswer2", Fanswer2);
cmd.Parameters.AddWithValue("#Fanswer3", Fanswer3);
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
return result;
}
result is still 0;
i know the problem where it was .
if the connection is closed the query will be executed successfully , but if it is opend it will not be executed due to this condition .
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
it must be
if (con.State != ConnectionState.Open)
{
con.Open();
}
result = cmd.ExecuteNonQuery();
con.Close();
thanks all .