Sqlite error (missing database) while trying to update jtable - java

private void checkKeyPressed(java.awt.event.KeyEvent evt) {
try{
String ch ="select * from check where name like ?%";
PreparedStatement pst=conn.prepareStatement(ch);
pst.setString(1, check.getText());
ResultSet rs=pst.executeQuery();
checker.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
above is the code im using, and im getting a:
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (near "check": syntax error)
i have a table named check in sqlite, and im trying to create a search engine in my jframe, so when i enter text in a textfield the jtable filters automatically. any idea why this error could come about.

You have to change this part, if you need to pass % you have to pass it with set Method and as check is a reserved keyword in sqlite change it to check
String ch ="select * from check where name like ?%";
PreparedStatement pst=conn.prepareStatement(ch);
pst.setString(1, check.getText());
with
String ch ="select * from `check` where name like ?";
PreparedStatement pst=conn.prepareStatement(ch);
pst.setString(1, check.getText()+"%");

Related

unrecognized problem in java using oracle

b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
user=tf1.getText();
pass=new String(tf2.getPassword());
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","jashan","noor1032");
PreparedStatement stmt=con.prepareStatement("select * from jashan.student where 'name1'=? and 'password'=?");
stmt.setString(1, user);
stmt.setString(2, pass);
ResultSet Rs=stmt.executeQuery();
if(Rs.next())
{
JOptionPane.showMessageDialog(f, "success!!");
}
else
{
JOptionPane.showMessageDialog(null, "incorrect username/password","warning",JOptionPane.WARNING_MESSAGE);
}
}
catch(Exception f)
{
System.out.println(f);
}
}
actually, i want that the code matches the username and password, but it is not doing so...whenever i execute, it shows invalid password/username....i don't know why....i have a table in oracle 11g which has columns student_id, name1,gender,address, email_id, phone_number,and password in the same order as defined. can anyone tell me what is the problem??
You have given single qoute around your column name that is causing the issue. Remove that and it should work
Change 'name1' to name1 and 'password' to password in your query
You have managed to create a table with lowercase column names. As you have experienced, it causes trouble as Oracle converts all names (for tables, columns etc.) to upper-case by default.
You have two options:
Drop the table and recreate it with uppercase names.
Use double quotes around the columns names to prevent Oracle from converting them to uppercase:
select * from jashan.student where "name1"=? and "password"=?
Or when you put it in Java:
PreparedStatement stmt = con.prepareStatement("select * from jashan.student where \"name1\"=? and \"password\"=?");
In any case, single quotes around column names is incorrect.

how to add sql parametrized queries through jdbc java

I have to develop a parameterized sql staement something like this below
select * from tablename where cid = cid
so below is the rest service which is calling a method so the user is passing the input parameters like tablename and cid and basis on that it
will go to database and to that particular table and will retrieve the coulmn values so below is the code now in the below code please advise
how can i change the sql statement to be parametrized so that it will retrieve the value from the table onm the basis of cid input by the user
public String retriveData(#QueryParam("tablename") String tablename,#QueryParam("cid") String cid ) throws SQLException
{
Connection con=null;
PreparedStatement ps=null;
String statement="";
String retString="";
try {
//Class.forName("com.mysql.jdbc.Driver");
//put sql jdbc jar in tomcat lib
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=DriverManager.getConnection("jdbc:sqlserver://xxx:1111; databaseName=aaa", "rr","vvv");
con.setAutoCommit(false);
System.out.println("FROM TABLE NAME : "+tablename);// ***** need to be parametrized query basis on the cid ******
statement="SELECT * FROM "+tablename+";";// ***** need to be parametrized query basis on the cid ********
System.out.println("STATEMENT : "+statement);
ps=con.prepareStatement(statement);
// Turn use of the cursor on.
//ps.setFetchSize(50);
ps.setMaxRows(10);
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
String name=rsmd.getColumnName(5);
while(rs.next())
{
retString=retString+name+" : "+rs.getString(name)+"<br>";
System.out.println(retString);
}
You can't. You need to contruct the sql with string concatenation/placeholder with String.format. prepared statement is for the column values not for table name.
Sources: How to use a tablename variable for a java prepared statement insert
How to pass table name to a Prepared Statement in a SELECT COUNT query?
I'm not sure about why you wanted to parametrized the table name.
But parametrized for cid is OK by using the prepared statement like below.
statement="SELECT * FROM " + tablename + " where cid = ?";
preparedStatement.setInt(1, cid);
If you want to retrieve values from specific table by filtering with cid, that will be the answer I guess.

Java Preparedstatement error when reading from MySql Database

I'm working on a simple application that pulls data from a local database. The below code works fine when I use a string for the SQL query, but I can not get it to work with PreparedStatement. I have reviewed similar problems posted here but most of those were caused by doing this, preparedStmt.executeQuery(query); instead of this preparedStmt.executeQuery(); Here is the code,
private final String POSTTITLE= "posttitle"; // DB Column name
private final String POSTCONTENT= "content"; // DB Column name
public String getDbContent(){
try{
String query ="select values(?, ?) from blog";
PreparedStatement preparedStmt = this.connect.prepareStatement(query);
preparedStmt.setString (1,POSTTITLE);
preparedStmt.setString (2,POSTCONTENT);
ResultSet rs = preparedStmt.executeQuery();
rs.next();
return(rs.getString(this.POSTCONTENT)); //Will replace with loop to get all content
} catch(Exception e) {
System.err.println("Error Reading database!");
System.err.println(e);
return("Error: "+e);
}
}
This is the error I get:
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 ''posttitle', 'content') from blog' at line 1
Parameters in prepared statements are for values - you're trying to use them to select fields. They just don't work that way.
In this very specific instance, you'll need to make the SQL dynamic. However, you'll want to make sure that whatever code you have to allow your columns to be specified is tightly constrained to avoid SQL injection attacks. (For example, you could have an enum with the columns in, or a whitelist of allowed values.)
Try concatenating select query:
String query ="select "+POSTTITLE+","+POSTCONTENT+" from blog";
Remember that prepared statements are for values, not query parameters, for them we use simply concatenations.
Try this:
String query ="select POSTTITLE, POSTCONTENT from blog";
PreparedStatement preparedStmt = this.connect.prepareStatement(query);
ResultSet rs = preparedStmt.executeQuery();
rs.next();
There is no need to use field names as parameter.

jTable connected to MySQL button error

i have the following jframe :
and i wanna make the buttons work im still new to programming can someone help me please? i want the add row btn to add a new row to database, the update btn let me save changes and delete delete the selected row, also the jTextBoxes are connected to the database
i tried doing this to update :
Connection conn=null;
PreparedStatement pst = null;
try{
String value1=txt_cid.getText();
String value2=txt_carid.getText();
String value3=txt_aid.getText();
String value4=txt_rd.getText();
String value5=txt_bd.getText();
String value6=txt_bn.getText();
String sql="update booking set customer_id'"+value1+"',car_id'"+value2+"',agency_id'"+value3+"',return_date'"+value4+"',booking_date'"+value5+"',booking_number'"+value6+"',";
pst=conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "table updated");
}catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
but it didnt work out for me i get exception error
You haven't stated what the error is but UPDATE takes an equals operator for every parameter. Also use PreparedStatement placeholders to avoid SQL Injection attacks:
String sql = "update booking set customer_id=?, car_id=?,agency_id=?,return_date=?,booking_date=?,booking_number=?";
pst = conn.prepareStatement(sql);
pst.setInt(1, value1);
pst.setInt(2, value2);
... // set the other parameters
Read: UPDATE Syntax

Oracle Java SQL Exception Error: ORA-0094

I am trying to write a function for this button. I want to be able to pass it a textfield value and be able to go into my database to retrieve some information.....
Can somebody explain to me what is going on and provide me a solution to this madness?
Thank you all xD
I keep running into this stupid problem:
ACTION1 createdoracle.jdbc.driver.T4CConnection#484845aa
Exception:java.sql.SQLSyntaxErrorException: ORA-00904: "ART": invalid identifier
Code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//CLASS TYPE
//LIST ALL OFFERED CLASSES AND REVENUE
try{
String classtype = jTextField1.getText().trim();
if(classtype.equals("")){
JOptionPane.showMessageDialog(this, "Sorry Wrong input.... Please try again....");
}
else if(classtype != ""){
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection(
"jdbc:oracle:thin:#fourier.cs.iit.edu:1521:orcl",
"usr","pwd");
Statement stmt = conn.createStatement();
System.out.println("ACTION1 created"+conn+"\n\n");
String ct = jTextField1.getText().trim();
//String aa = "SELECT * FROM CLASS WHERE TYPE="+classtype;
//System.out.println(aa);
ResultSet rset = stmt.executeQuery("SELECT * FROM CLASS WHERE TYPE="+ct);
while (rset.next()) {
System.out.println(rset.getString("TITLE") + " ");
}
JOptionPane.showMessageDialog(this, "Class Type: "+classtype);
stmt.close();
conn.close();
System.out.println("Connection Closed");
}
catch(Exception sqle){
System.out.println("\nException:"+sqle);
}
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, "Please Retry input....", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Let me guess ... does the ct String start with "ART" (or some variation)?
If so, the problem is that SQL requires quotes around string literals. Your query probably looks to Oracle something like this:
SELECT * FROM CLASS WHERE TYPE=Art of War
but it should look like
SELECT * FROM CLASS WHERE TYPE='Art of War'
There are two ways to fix this:
Assemble the query with quote characters around ct.
Write the query as "SELECT * FROM CLASS WHERE TYPE=?", use a PreparedStatement instead of a Statement and use the setString method to supply the parameter value.
If done properly, the second approach is both more secure and more efficient. (The problem with string-bashing the query and using Statement is that you are potentially making yourself vulnerable to SQL injection attacks.)
You're passing the value as part of the query, and the string concatenation you're doing makes the SQL into:
SELECT * FROM CLASS WHERE TYPE=ART
(where ART is the value of ct from the textfield) so it's trying to find a column on the table called ART. At an absolute minimum you need to quote the string:
ResultSet rset = stmt.executeQuery("SELECT * FROM CLASS WHERE TYPE='" + ct + "'");
But really don't do this; as #Andreas_D says you're leaving yourself open to SQL injection. Always use prepared statements and bind variables:
String sql = "SELECT * FROM CLASS WHERE TYPE=?";
PrepareStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ct);
ResultSet rset = stmt.executeQuery();

Categories

Resources