jdbc application update sql isnt working for me, any ideas - java

public void Update(String name, String mobile, String email, String car, String model, String year, String color, String plate_no, String plateletters,String gear, String km, String date,String licesnse,String status, String notes){
Connection conn = null;
try{
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("connected");
Statement stmt = (Statement) conn.createStatement();
String ins = "update car"
+ "set Name = '"+name+"' , "
+ "Email = '"+email+"' , "
+ "Car = '"+car+"' , "
+ "Model = '"+model+"' , "
+ "Year = '"+year+"' , "
+ "Color = '"+color+"' , "
+ "Plateno = '"+plate_no+"' , "
+ "Plateletters = '"+plateletters+"' , "
+ "Gearbox = '"+gear+"' , "
+ "Km = '"+km+"' , "
+ "Date = '"+date+"' , "
+ "License = '"+licesnse+"' , "
+ "Status = '"+status+"' , "
+ "Notes = '"+notes+"' "
+ "where Mobile = '"+mobile+"' ";
stmt.execute(ins);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e.getMessage());
System.err.println(e);
return;
}
}
**i have tried prepared statment and stmt.executeUpdate(ins); but nothing workes !!
Please help!**
the error :
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= 'ahmed' , Email = 'ahmed#hotmail.com' , Car = 'honda' , Model = 'hondaz' , Yea' at line 1

You need to make sure you add proper space between elements in your SQL query:
String ins = "update car"
should be
String ins = "update car "
A good approach to doing this is to write and execute your SQL in your database query tool (SQL developer, phpMyAdmin, whatever) and make sure your syntax is good before trying to re-write it in Java.

Use a preparedStatement instaed of a Statement.
Connection conn = null;
try{
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
PreparedStatement pstm = conn.prepareStatement(
"update car "
+ "set Name = ? ,"
+ "Email = ? ,"
+ "Car = ? ,"
+ "Model = ? ,"
+ "Year = ? ,"
+ "Color = ? ,"
+ "Plateno = ? ,"
+ "Plateletters = ? ,"
+ "Gearbox = ? ,"
+ "Km = ?,"
+ "Date = ?,"
+ "License = ?, "
+ "Status = ?, "
+ "Notes = ? "
+ "where mobile = ?"
);
pstm.setObject(1, name);
pstm.setObject(2, email);
pstm.setObject(3, car);
pstm.setObject(4, model);
pstm.setObject(5, year);
pstm.setObject(6, color);
pstm.setObject(7, plate_no);
pstm.setObject(8, plateletters);
pstm.setObject(9, gear);
pstm.setObject(10, km);
pstm.setObject(11, date);
pstm.setObject(12, licesnse);
pstm.setObject(13, status);
pstm.setObject(14, notes);
pstm.setObject(15, mobile);
pstm.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}

Related

Error: com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range

I have a function to update the user's information as follows:
public void updateAccount(String username, String name, String address, String aboutMe, String
id) {
String sql = "update Account set username = '?', \n"
+ " [Full_Name] = '?',\n"
+ " [Address] = '?',\n"
+ " [about_me] = '?'\n"
+ " where id = ?";
try {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, name);
ps.setString(3, address);
ps.setString(4, aboutMe);
ps.setString(5, id);
ps.executeUpdate();
} catch (Exception ex) {
Logger.getLogger(AccountDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
and this code is giving me an error like this:
Severe: com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(SQLServerPreparedStatement.java:933)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setValue(SQLServerPreparedStatement.java:948)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(SQLServerPreparedStatement.java:1578)
at dao.AccountDao.updateAccount(AccountDao.java:117)
at controller.UserProfileController.doPost(UserProfileController.java:91)
I don't understand why it gives me the error "The index 2 is out of range" and is there any
way to fix it?
Don't enclose ? parameter markers in quotes. These are typed by the appropriate setter:
String sql = "update Account set username = ?, \n"
+ " [Full_Name] = ?,\n"
+ " [Address] = ?,\n"
+ " [about_me] = ?\n"
+ " where id = ?";

How do I insert local variable MySQL using JDBC

public class DataBase {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/company", , )) {
Type[] types = { new GraphicCard(), new HardDrive(), new Keyboard(), new Memory(), new Monitor(), new Mouse(), new Processor() };
Product product = new Product(10, types);
Range rangeUnitPrice = new Range(10_000, 220_000);
Range rangeQuantity = new Range(0, 20);
Statement statement = connection.createStatement();
while (product.getNumberOfEntery() > 0) {
String typeAndCatagory = product.getRandomType();
String name = product.getName(typeAndCatagory);
String description = product.getDescription();
double unit_Price = product.randomUnit_PriceGenerator(name, 'x', rangeUnitPrice);
int quantity_In_Stock = product.generateQuantity_In_Stock(rangeQuantity);
String brand = product.getRandomBrand();
System.out.println("Name: " + name + ", " + "Type: " + typeAndCatagory + ", " + "Random price: " + unit_Price + ", " + "Quantity in stock: " + quantity_In_Stock + ", " + "Random brand: " + brand);
String query = "INSERT INTO product VALUES (" + name + ", " + description + ", " + unit_Price + ", " + quantity_In_Stock + ", " + brand + ", " + typeAndCatagory + ", " + typeAndCatagory + ")";
statement.executeUpdate(query);
product.decreasesNumberOfEntrees();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The query doesn't work, and the first value is the default (PRIMARY KEY AUTO-INCREMENT), which I don't need to specify. The error is below
java.sql.SQLSyntaxErrorException: You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near '10 AMD graphic card Gamer Edition, ,
180657.63138583858, 6, HP, Graphic Card, Gr' at line 1
You format a string in this line to use as an SQL statement:
String query = "INSERT INTO product VALUES (" + name + ", " + description + ", " + unit_Price + ", " + quantity_In_Stock + ", " + brand + ", " + typeAndCatagory + ", " + typeAndCatagory + ")";
Something is wrong with this statement that makes it produce a syntax error. What is wrong?
It's difficult to debug this by staring at the Java expression. It's confusing to look at all the " and + and see what's wrong.
It would be easier to see what's wrong if you can see the final result of the string, not the Java expression that builds a string.
So before you execute it, try printing it out:
System.out.println(query);
Then the problem may be more clearly visible.
I predict it will look something like this:
INSERT INTO product VALUES (10 AMD graphic card Gamer Edition, , 180657.63138583858, 6, HP, Graphic Card, Gr...
This is missing quotes around the string values in your VALUES clause. It's not valid SQL.
The best solution is to learn to use query parameters. Then you don't have to worry about quotes around values. And the code is more secure from SQL injection.
In your case, something like the following:
String query = "INSERT INTO product VALUES (?, ?, ?, ?, ?, ?, ?)";
Statement statement = connection.prepareStatement(query);
while (product.getNumberOfEntery() > 0) {
// set the values for all your variables...
statement.setString(1, name);
statement.setString(2, description);
statement.setDouble(3, unit_Price);
statement.setInt(4, quantity_In_Stock);
statement.setString(5, brand);
statement.setString(6, typeAndCatagory);
statement.setString(7, typeAndCatagory);
statement.executeUpdate();
}
There are two problems with your code:
The major one is, your code is vulnerable to SQL Injection.
You will have to enclose the text values withing single quotes yourself.
The solution to both the problem is using PreparedStatement as shown below:
String query = "INSERT INTO product VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = con.prepareStatement(query)) {
//...
pstmt.setString(1, name);
pstmt.setString(2, description);
pstmt.setDouble(3, unit_Price);
//...
pstmt.executeUpdate();
}
Also, I suggest you always follow Java naming conventions e.g. unit_Price should be named as unitPrice.

SQLite java.lang.NullPointerException in only select query

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

SQL logic error or missing database in Blackberry programming

I am trying to insert data into a SQLite database from a blackberry. When I call the screen I also call a method to create the database:
boolean sdCardPresent = false;
public static Database sqliteDB;
URI uri;
public void createdatabase()
{
try{
Enumeration e = FileSystemRegistry.listRoots();
root = (String)e.nextElement();
Dialog.inform(root);
if(root.equalsIgnoreCase("sdcard/"))
{
sdCardPresent = true;
}
if(!sdCardPresent)
{
Dialog.inform("O seu dispositivo nao suporta este compartimento sem cartao de memoria, verifique se existe um SD card no seu dispositivo.");
UiApplication.getUiApplication().pushScreen(new Tab_Main());
}else{
uri = URI.create(
"file:///SDCard/Databases/MBA.db");
sqliteDB = DatabaseFactory.openOrCreate(uri);
sqliteDB = DatabaseFactory.open(uri);
Statement st = sqliteDB.createStatement("DROP TABLE IF EXISTS atms;CREATE TABLE atms " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT ," +
" localizacao TEXT, " +
" mapa TEXT ," +
" foto1 TEXT ," +
" foto2 TEXT," +
" zona TEXT);" +
"" +
"DROP TABLE IF EXISTS balcoes;CREATE TABLE balcoes " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT ," +
" localizacao TEXT, " +
" mapa TEXT ," +
" foto1 TEXT ," +
" foto2 TEXT," +
" zona TEXT);" +
"" +
"DROP TABLE IF EXISTS contactos;CREATE TABLE contactos " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT ," +
" nome TEXT, " +
" numero_conta INTEGER);") ;
st.prepare();
st.execute();
st.close();
sqliteDB.close();
Dialog.inform("Status: Database was successfully created.");
//}
} catch (Exception e){
System.out.println(e.getMessage());
Dialog.inform("\n "+e);
//UiApplication.getUiApplication().popScreen(Screen);
}
}
After that I use some Editfields and other components to get the values. I call the method to insert the parameters and send the query:
public void insert_update(String query) {
try {
sqliteDB = DatabaseFactory.openOrCreate(uri);
Statement st = sqliteDB.createStatement(query);
//Statement statement = _db.createStatement(query);
st.prepare();
st.execute();
st.close();
Dialog.inform("Adicionado com sucesso!!!");
}
catch ( Exception e ) {
Dialog.inform(e+"");
}
}
For example when I call it with the query = "insert into contactos values (null,"a","1"); I get an exception. SQL logic error or missing database.
Try dropping the quotes around the third column value.
INSERT INTO contactos VALUES (null,"a", 1);
It's defined as an INTEGER.
numero_conta INTEGER
EDIT :
System.out.println(uri); // check if null, or different
if (uri == null) {
uri = URI.create(
"file:///SDCard/Databases/MBA.db");
}
sqliteDB = DatabaseFactory.openOrCreate(uri);
sqliteDB = DatabaseFactory.open(uri); // open again
Statement st = sqliteDB.createStatement(query);

MySQLSyntaxErrorException: Unknown column ' ____ ' in 'field list'

I get the following MySQL exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'book.call_Number' in 'field list'.
What does that mean and how can I solve it?
Here is the code responsible for this exception:
public void actionPerformed(ActionEvent e) {
list.clearSelection();
String selectString = " ";
String afName = auth_fName.getText();
String aMI = auth_MI.getText();
String alName = auth_lName.getText();
String tField = titleField.getText();
String sField = subjectField.getText();
try {
Connection conn = Database.getConnection();
Statement s = conn.createStatement();
if (!afName.equals("") && (!aMI.equals("")) && (!alName.equals("")) && (!tField.equals("")) && (!sField.equals(""))) {
selectString = "SELECT a.call_Number as callNbr "
+ "FROM book a "
+ "FULL JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
}
s = conn.createStatement();
System.out.println(selectString);
ResultSet rs = s.executeQuery(selectString);
while (rs.next()) {
String call_Num = rs.getString("call_Number");
String title = rs.getString("title");
String auth_lName = rs.getString("auth_lName");
String auth_MI = rs.getString ("auth_MI");
String auth_fName = rs.getString("auth_fName");
String availability = rs.getString("availability");
view = new View(call_Num, title, auth_lName, auth_MI, auth_fName, availability);
vList.add(view);
System.out.println(view);
}
rs.close();
s.close();
conn.close();
list.setListData(vList.toArray());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Here is the DDL and content:
s.executeUpdate (
"CREATE TABLE book ("
+ "call_Number CHAR(10),"
+ "PRIMARY KEY (call_Number),"
+ "auth_fName CHAR(30)NOT NULL, auth_MI CHAR(2),"
+ "auth_lName CHAR(50)NOT NULL, title CHAR(100) NOT NULL,"
+ "subject CHAR(30) NOT NULL)");
count = s.executeUpdate (
"INSERT INTO book"
+ " VALUES"
+ "('MY.111.000', 'Mark', 'M','Bradshaw','Mystery Under the Sun','mystery'),"
+ "('MY.111.001', 'Mark','','Twain','The Adventures of Huckleberry Finn','mystery'),"
+ "('SF.111.002', 'Kito', 'M','Bradford','Mr. Roboto','science fiction'),"
+ "('SF.111.003', 'Eric','','Laslow','Science Fiction - Can It Happen?','science fiction'),"
+ "('AV.111.004', 'Rashad','','Cheeks','Fire Under the Bridge','adventure'),"
+ "('AV.111.005', 'Samantha','A','Appleby','The Open Sea','adventure'),"
+ "('CO.111.006', 'Lindsey', '','Butterby','What? We cant spend anymore!?','comedy'),"
+ "('CO.111.007', 'Judy', 'S','Yates','So this is life?','comedy'),"
+ "('IN.111.008', 'Elizabeth', 'J','Lee','Mystery Under the Sun','international'),"
+ "('IN.111.009', 'Gabriella', 'M','Rodriguez','Love in Brazil','international')");
*******t_action table***************************
//create transaction table
s.executeUpdate (
"CREATE TABLE t_action ("
+ "patron_ID CHAR(10) NOT NULL,"
+ "call_Number CHAR(10) NOT NULL, check_Out_Date DATE NOT NULL, check_In_Date DATE NOT NULL,"
+ "PRIMARY KEY (patron_ID, call_Number),"
+ "avail CHAR(15), total_Charge FLOAT)");
count3 = s.executeUpdate (
"INSERT INTO t_action"
+ " VALUES"
+ "('P222200000','MY.111.000','2011-03-08','2011-03-15','AVAILABLE',5.00),"
+ "('P222200001','MY.111.001','2011-03-31','2011-04-6','DUE 2011-04-6',5.00),"
+ "('P222200002','SF.111.002','2011-03-30','2011-04-5','DUE 2011-04-5',5.00),"
+ "('P222200003','SF.111.003','2011-03-29','2011-04-4','DUE 2011-04-4',5.00),"
+ "('P222200004','AV.111.004','2011-03-28','2011-04-3','DUE 2011-04-3',5.00),"
+ "('P222200005','AV.111.005','2011-03-27','2011-04-2','DUE 2011-04-2',5.00),"
+ "('P222200006','CO.111.006','2011-03-26','2011-04-1','DUE 2011-04-1',5.00),"
+ "('P222200007','CO.111.007','2011-01-06','2011-01-12','AVAILABLE',5.00),"
+ "('P222200008','IN.111.008','2011-02-06','2011-02-12','AVAILABLE',5.00),"
+ "('P222200009','IN.111.009','2011-03-06','2011-03-12','AVAILABLE',5.00)");
Use a <column> as predicate like below:-
selectString = "SELECT a.call_Number as callNbr, ... "
+ "FROM book a"
+ "FULL JOIN transaction b"
+ "ON a.call_Number=b.call_Number";
And then change the code to look for callNbr :-
String call_Num = rs.getString("callNbr");
HTH.
Change your query to this:
selectString = "SELECT a.call_Number "
+ "FROM book a "
+ "INNER JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
MySQL does not support FULL OUTER JOIN. If you really need the effect of that - you'll need 2 selects with a UNION. Although from looks of it - does not seem like that would be necessary.

Categories

Resources