Java JDBC SQLite update entry not working - java

I have created a database and a set of table using JDBC and SQLite in Eclipse.
I am trying to update the table using the following code:
public static void update()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "UPDATE CUSTOMERS2 set ADDRESS = Byron WHERE PHONE=2;";
stmt.executeUpdate(sql);
c.commit();
ResultSet rs = stmt.executeQuery( "SELECT * FROM CUSTOMERS;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Update Completed successfully");
}
As far as I can understand the SQL syntax I m using says:
update the table customers2 and set the address as Byron where phone =2
But am getting the following error:
java.sql.SQLException: no such column: Byron
Which tells me it is interpreting my request as asking to alter the column named Byron, which is not what I believe the code to be saying?

As per SQL syntax, varchar values should be used with single quotes so update this:
String sql = "UPDATE CUSTOMERS2 set ADDRESS = Byron WHERE PHONE=2;";
to
String sql = "UPDATE CUSTOMERS2 set ADDRESS = 'Byron' WHERE PHONE=2;";
If you don't use the single quotes, SQL assumes that you are trying to set the value using a different column and hence it throws the error:
java.sql.SQLException: no such column: Byron
ADVICE: Use PreparedStatment for dynamic parameter queries
PreparedStatement stmt;
String sql = "UPDATE CUSTOMERS2 set ADDRESS=? WHERE PHONE=?";
stmt = c.prepareStatement(sql);
stmt.setString(1, "Byron");
stmt.setInt(2, 2);
stmt.executeUpdate();

Related

Selecting a row from sql database based on a value in a specific column in java

I'm currently working on a project where we have an inventory for an optical lens company which is stored in a database. I've connected my database to my java program and im just having an issue selecting a row based on a column value. Im doing this by
String name=lookUpName.getText();
try (
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/productitem?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
"root", "123456789"); // for MySQL only
Statement stmt = conn.createStatement();
) {
String strSelect = "select * from products where productName= "+name+"";
System.out.println("The SQL statement is: " + strSelect + "\n"); // Echo For debugging
ResultSet rset = stmt.executeQuery(strSelect);
}
rset.close();
when it tries to execute the query it gives me an error. but if i run a regular query using the sql console like select *
from products where productName='golden vintage'; it works. can someone help me with the java part.
the debugging output i have in there shows
The SQL statement is: select * from products where productName= golden vintage
The error I get is:
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 'vintage' at line 1
I figured it out using the Prepared Statements
String strSelect = "select * from products where productName= ?";
PreparedStatement st = conn.prepareStatement(strSelect);
st.setString(1,name);
ResultSet rs = st.executeQuery();
while (rs.next()) {
String productid = rs.getString(1);
String productColors=rs.getString(2);
String productPrices = rs.getString(3);
String productBrands=rs.getString(4);
String productStyles = rs.getString(5);
String productNames=rs.getString(6);
System.out.println(productid +" "+productNames + " " +productBrands + " " + productStyles + " " + productColors + " " + productPrices);
}

Don't know how to convert to string and print ResultSet, SELECT statement

This is a small piece of my code. Basically, i do not know how to print my ResultSet or turn it into string.
try {
String url = "jdbc:odbc:" + "userstuff";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url,"","");
// Gets a statement
Statement state = con.createStatement();
String query = "SELECT description FROM topics WHERE title = '" + title + "'";
String query2 = "SELECT * FROM comment WHERE topic = '" + title + "'";
// selects the description for the selected topic ( title will be referenced to the chosen topic)
ResultSet results = state.executeQuery(query);
// selects * of the rows from "comment" table where the topic equals the selected title.
ResultSet results2 = state.executeQuery(query2);
desc = results.toString();
}
You can not convert ResultSet to string neither you can print directly from ResultSet.
Following code may help you.
try {
String url = "jdbc:odbc:" + "userstuff";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url,"","");
// Gets a statement
Statement state1 = con.createStatement();
Statement state2 = con.createStatement();
String query1 = "SELECT description FROM topics WHERE title = '" + title + "'";
// selects the description for the selected topic ( title will be referenced to the chosen topic)
ResultSet results1 = state1.executeQuery( query1 );
while( results.next() ){
System.out.println( results1.getString( "description" );
}
// selects * of the rows from "comment" table where the topic equals the selected title.
String query2 = "SELECT * FROM comment WHERE topic = '" + title + "'";
ResultSet results2 = state2.executeQuery( query2 );
while( results2.next() ){
System.out.println( results2.getString( 1 ); // here 1 is tables 1st column
System.out.println( results2.getString( 2 ); // here 2 is tables 2nd column
}
} Exception( SQL e){
e.printStackTrace();
}

Table/View 'ACCOUNTS' already exists in Schema 'APP'

I'm not an experienced database developer.
Running a JDBC program with org.apache.derby.jdbc.EmbeddedDriver. When I try to create an ACCOUNTS table, I use the following code:
final String DRIVER =
"org.apache.derby.jdbc.EmbeddedDriver";
final String CONNECTION =
"jdbc:derby:AccountDatabase;create=true";
try {
Class.forName(DRIVER).newInstance();
} catch ( ... etc.
}
try (Connection connection =
DriverManager.getConnection(CONNECTION);
Statement statement =
connection.createStatement()) {
statement.executeUpdate(
"create table ACCOUNTS "
+ " (NAME VARCHAR(32) NOT NULL PRIMARY KEY, "
+ " ADDRESS VARCHAR(32), "
+ " BALANCE FLOAT) ");
But I get the following error message:
Table/View 'ACCOUNTS' already exists in Schema 'APP'.
Then, when I try to update or query the ACCOUNTS table with the following code:
final String DRIVER =
"org.apache.derby.jdbc.EmbeddedDriver";
final String CONNECTION =
"jdbc:derby:AccountDatabase";
try {
Class.forName(DRIVER).newInstance();
} catch ( .. etc.
}
try (Connection connection =
DriverManager.getConnection(CONNECTION);
Statement statement =
connection.createStatement();
ResultSet resultset =
statement.executeQuery(
"select * from ACCOUNTS")) {
I get the following error messages:
java.sql.SQLException: Database 'AccountDatabase' not found.
Also, when I check for the existence of any tables with the following code, I get no tables at all:
DatabaseMetaData meta = connection.getMetaData();
ResultSet res = meta.getTables(null, null, null,
new String[] { "TABLE" });
System.out.println("List of tables: ");
while (res.next()) {
System.out.println(" " + res.getString("TABLE_CAT") + ", "
+ res.getString("TABLE_SCHEM") + ", "
+ res.getString("TABLE_NAME") + ", "
+ res.getString("TABLE_TYPE") + ", "
+ res.getString("REMARKS"));
}
Any suggestions?

java.sql.SQLSyntaxErrorException: Syntax error: Encountered "80" at line 1, column 1100

I get the following exception,
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "80" at line 1, column 1100.
when I try to insert like the following! Any idea what this could mean??!
String insertString = "insert into queries (data_id, query, "
+ "query_name, query_file_name, status) values(" + currentDataID + ", '"
+ params[1] + "', '" + params[2] + "', '"
+ params[3] + "', '" + params[4] + "')";
try {
Statement stmt = dbconn.createStatement();
stmt.execute(insertString, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
if (rs != null && rs.next()){
currentDataID = (int) rs.getLong(1);
}
} catch (SQLException ex) {
}
Table definition,
CREATE TABLE queries (query_id INT not null primary key GENERATED "
+ "ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), data_id "
+ "INTEGER not null, foreign key (data_id) references data "
+ "(data_id), query LONG VARCHAR, query_name VARCHAR(150), "
+ "query_file_name VARCHAR(150),status VARCHAR(20))
Try this approach with a prepared statement:
String insert = "INSERT INTO queries (data_id, query, query_name," +
" query_file_name, status) VALUES (?,?,?,?,?)";
PreparedStatement stmt = dbconn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
// Why do you set this if you want the DB to generate it?
stmt.setInt(1, currentDataID); // or setLong() depending on data type
stmt.setString(2, params[1]); // I assume params is a String[]
stmt.setString(3, params[2]);
stmt.setString(4, params[3]);
stmt.setString(5, params[4]);
stmt.execute();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
// if it's an int, avoid the cast and use rs.getInt(1) instead
currentDataID = (int) rs.getLong(1);
}
I don't understand why you set the data_id while the later code expects the database to generate it... Your table definition would help.
This is probably happening because one of your params[] contains a quote character.
This problem is exactly why you shouldn't create SQL expressions like this, but should instead use a PreparedStatement. Please read up on SQL injection.

How to insert reference values in database using JDBC?

I am trying to insert values into Oracle 10g database using the code below but its giving an error of "Missing Expression" on execution. I have to pass reference values into the insert clause but do not know the exact syntax or way of doing it.
Please help me through this.
Thanks.
Student Table:-
Sid VARCHAR2(200) PRIMARY KEY CHECK(Sid>0),
Pass_word VARCHAR2(10) NOT NULL,
S_name VARCHAR2(20) NOT NULL,
G_name VARCHAR2(20) ,
Branch VARCHAR2(10) NOT NULL,
D_company VARCHAR2(20) ,
B_Percent INT NOT NULL CHECK(B_Percent<100),
twelth_percent INT NOT NULL CHECK(twelth_percent<100),
tenth_percent INT NOT NULL CHECK(tenth_percent<100),
Certify VARCHAR2(30),
Semester INT NOT NULL CHECK(Semester<9),
D_Birth DATE NOT NULL,
Sex VARCHAR2(6) NOT NULL
CODE:
Connection connection = null;
try
{
// Load the JDBC driver
String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driverName);
connection = DriverManager.getConnection("jdbc:odbc:placement","siddharth","sid");
studentID = StudentID.getText();
spassword = PasswordField.getPassword();
studentname = NameField.getText();
Gname = GuardianField.getText();
branch = BranchField.getText();
dcompany = DcompanyField.getText();
bpercent = BtechField1.getText();
twelthpercent = TwelthField.getText();
tenthpercent = TenthField.getText();
semester = SemesterField.getText();
certify = CertificationField.getText();
sex = SexCombo.getActionCommand();
date = (Date) DateTextField1.getValue();
Statement stmt = connection.createStatement();
stmt.executeUpdate("insert into student " +"(sid,pass_word,s_name,g_name,branch,d_company,b_percent,twelth_percent,tenth_percent,certify,semester,d_birth,sex)"+
"values(studentID, spassword,studentname,Gname,branch,dcompany,bpercent,twelthpercent,tenthpercent,certify,semester,date,sex)" );
stmt.close();
connection.close();
}
catch (ClassNotFoundException e) {
// Could not find the database driver
JOptionPane.showMessageDialog(null,e);
}
catch (SQLException e) {
// Could not connect to the database
JOptionPane.showMessageDialog(null,e);
}
Currently your SQL statement looks like:
insert into student (sid, pass_word, ...) values (studentID, spassword, ...)
The variable names mean nothing to the SQL itself.
You should use a prepared statement. For example, your SQL should look like this:
insert into student (sid, pass_word, ...) values (?, ?, ...)
and then you use:
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, studentID);
stmt.setString(2, spassword);
// etc
See the JDBC tutorial on prepared statements for more information.
To be on the safe side you should use prepared statements.
Prepare the Query String
String updateString = "update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
Create a PrepartedStatement with this query:
updateSales = connnection.prepareStatement(updateString);
Fill the ? spaceholders with you values:
updateSales.setInt(1, myVariable1);
updateSales.setString(2, myVariable2);
execute the Query
updateSales.executeUpdate();

Categories