General error when trying to insert data into database - java

I am trying to insert data into a database and once again I cant seem to get to the bottom as to why I am getting a general error.
Any advice as to how to overcome this problem.
Class.forName(driverName);
connection = DriverManager.getConnection(SourceURL, user, password);
int rowAdded;
Object typeId = comboKeys.getSelectedItem();
String typeIdString = typeId.toString();
int typeIdInt = Integer.parseInt(typeIdString);
String animalIDString = txtAnimalID.getText();
int animalID = Integer.parseInt(animalIDString);
System.out.println(animalID);
String name = txtName.getText();
Statement statement = connection.createStatement();
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', '" + typeIdInt + "')";
rowAdded = statement.executeUpdate(queryString);
connection.close();
Kind regards
Arian

Error
You have typeIdInt as Integer, however in the sql query, you are stating it as string (because you surround it with single quotes)
Solution
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', '" + typeIdInt + "')";
should be :
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', " + typeIdInt + ")";
Look at " + typeIdInt + ". You have '" + typeIdInt + "'
Good Luck!!!

Related

inserting to database using java gui

I am trying to insert data from my netbeans to mysql workbench. there is no problem with the query but when I run the program a message box appear "Unknown column 'empJob' in 'field list '" . What seems to be the problem?
and just to Know i tried this on another table and it works just fine! but in this one it doesn't work!
int id, Salary;
String name, Address, Jop;
id = Integer.parseInt(tNo.getText());
name = tName.getText();
Address = tAddress.getText();
Jop = tJop.getText();
Salary = Integer.parseInt(tNo.getText());
String sql = "insert into employee(empid,empName, empAddress,empJob,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
int x = st.executeUpdate(sql);
if (x > 0) {
JOptionPane.showMessageDialog(prev, x + "rows effected");
} else {
JOptionPane.showMessageDialog(prev, "insert failed");
}
Do you have a typo? You write empJob -> but your variable is called Jop. So maybe it should be empJop.
String sql = "insert into employee(empid,empName, empAddress,empJop,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";

no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey

Log Cat:
no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
code:
102) public String getID(String note){
103) SQLiteDatabase db = this.getWritableDatabase();
104) String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = " + note);
105) db.rawQuery(query,null);
106) return query;
107) }
I do have a column name hey in my Database
Database Picture
Your terminology is confused.
hey is a value, NOTEMEMOS is a column.
You need to quote the value hey to let the SQL compiler know that it is a string value, rather than a column you are trying to compare against.
String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'");
Just a note, you would be better off using a parameterised query, as using raw values is insecure (see SQL injection).
String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?"); // That's right, quotes aren't needed for a parameterized query.
String result = "";
Cursor cursor = db.rawQuery(query,new String[] {note} );
if (cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(COL_0));
}
cursor.close();
return result;
Your query should look like this
SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = 'hey'
Let me know if it helps
The way that you concatenate the parameter note creates this sql statement:
SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
so hey is considered a column identifier and not a string literal because it is not enclosed inside single quotes.
You could do this instead:
String query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'";
and it would work.
But the recommended way is passing parameters as a string array like this:
String query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?";
Cursor cursor = db.rawQuery(query, new String[] {note});
return cursor;
This way you don't worry about single quotes as this is taken care of by rawQuery().
I guess you want to return the Cursor object and not the sql query string, right?

Java sql populating table and getting '.0' at the end

im using this code to populate my jtable with data from database:
String sql = "SELECT "
+ "a.pranesimo_pav AS 'Pavadinimas', a.sukurimo_data AS 'Sukurtas' , b.gavimo_data AS 'Gavimo data'"
+ "FROM Pranesimas a "
+ "INNER JOIN "
+ "( "
+ "SELECT pranesimo_id, gavimo_data "
+ "FROM Pranesimo_siuntimas_vienam_zmogui "
+ "WHERE vardas_pavarde = '" +vardas_pavarde+ "' "
+ "UNION ALL "
+ "SELECT pranesimo_id, gavimo_data "
+ "FROM Pranesimo_siuntimas_grupei "
+ "WHERE grupes_pav = '" +grupes_pav+ "'"
+ ")b ON a.pranesimo_id = b.pranesimo_id ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(sql);
antraspanelesamipranesimaiTable.setModel(DbUtils.resultSetToTableModel(rs));
}
It does the job, but at the end of my 'datetime' value, it adds '.0' at the end of it, for example:
value in database - '2013-01-20 02:50:00'
value i get in my table - '2013-01-20 02:50:00.0'
how can i fix this?

Android Insert Statement

I have create an android application where in users can add, update, and delete stuffs from the database
In my DataSource java file i have this code:
public void addWebsite(String sitename, String username, String password) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_URL, sitename);
values.put(MySQLiteHelper.COLUMN_USERNAME, username);
values.put(MySQLiteHelper.COLUMN_PASSWORD, password);
database.insert(MySQLiteHelper.TABLE_URL, null,values);
}
the above code makes the insert statement.
public void updateWebsite(WebsiteRecords website){
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_URL, website.getSitename());
values.put(MySQLiteHelper.COLUMN_USERNAME, website.getUsername());
values.put(MySQLiteHelper.COLUMN_PASSWORD, website.getPassword());
database.update(MySQLiteHelper.TABLE_URL, values, MySQLiteHelper.COLUMN_ID + " = " + website.getId(), null);
}
the above code displays an update statement
public void deleteWebsite(WebsiteRecords website) {
database.delete(MySQLiteHelper.TABLE_URL, MySQLiteHelper.COLUMN_ID + " = " + website.getId(), null);
}
and lastly, the above code is for the delete statement.
My problem is, I get this username from my login, and from that I want to add, update and delete stuffs which has the username i got from my login screen. I was thinking of making
Cursor mCursor = database.rawQuery("INSERT INTO " + TABLE_URL + " VALUES('" + sitename + "', '" + username + "', '" + password + "') " WHERE loginname=?", new String [] {loginname});
or anything like that but I am scared that it won't work. Same goes with the update and delete. It will only add, update, delete, view files which has a loginname of for instance "iamcoolin3d".
Anyone can help me with this?
The line:
Cursor mCursor = database.rawQuery("INSERT INTO " + TABLE_URL + " VALUES('" + sitename + "', '" + username + "', '" + password + "') " WHERE loginname=?", new String [] {loginname});
Should be:
Cursor mCursor = database.rawQuery("INSERT INTO " + TABLE_URL + " VALUES('" + sitename + "', '" + username + "', '" + password + "') WHERE loginname=?", new String [] {loginname});
there is an extra " before WHERE
There is a problem with your last line, you must put WHERE in the String, otherwise it won't work.

Sql update query with Single quotes

I am using hibernate application in java to retrieve and update database.
During updating a table,i forming an sql query as follows,
String qry = "UPDATE " + entity + " SET " + htmlColumn + " ='"+value+"' WHERE " + id + " = " + primaryId;
where value is a html string which contains single quotes sometimes.
How to escape ignore/escape the single quotes and update the table successfully
Thanks
use PreparedStatement for this
String qry = "UPDATE " + entity +
" SET " + htmlColumn + " = ? " +
"WHERE " + id + " = ?";
PreparedStatement pstmt = con.prepareStatement(qry);
pstmt.setString(1, value);
pstmt.setInt(2, primaryId);
pstmt.executeUpdate();
PreparedStatement
Don't set values directly.
currentSession()
.createQuery("UPDATE " + entity + " SET " + htmlColumn +
" = :value WHERE " + id + " :id")
.setParameter("value", value).setParameter(":id",id).executeUpdate();
You can replace the single quote with a double single quote. value.replace("'","''"); but you will need to cater for more than just that because your value can easily allow for SQL Injection if it is not properly catered for.
You can use preparedstatement as :
String query= "UPDATE " + entity + " SET " + htmlColumn + " =? WHERE " + id + " = " + primaryId;
PreparedStatement ptmt = con.prepareStatement(query);
ptmt.setString(1, value);

Categories

Resources