So I'm very new to java and SQL and they are my first programming languages. I am trying to do some work with JDBC. I want to allow for a user to input an id and return a query based on the variable. If someone could at least point me in the right direction... Here is the code I'm starting with. Mind you its crude but just trying to get a working piece of code so I can better implement it in my main class.
Scanner input = new Scanner(System.in);
Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Derek\\Documents\\Databases\\example.sqlite");
Statement stat = conn.createStatement();
PreparedStatement prep1 = conn.prepareStatement(
"insert into MedType values (?, ?);");
PreparedStatement prep2 = conn.prepareStatement(
"insert into Media values (?, ?,?, ?,?, ?);");
System.out.print("Please choose a database(MedType or Media): ");
String db=input.next();
if(db.equalsIgnoreCase("MedType"))
{
System.out.print("Enter in ID: ");
String answer1 = input.next();
System.out.print("");
String answer2 = input.nextLine();
System.out.print("Enter in Description: ");
String answer3 = input.nextLine();
prep1.setString(1, answer1);//add values into cell
prep1.setString(2, answer3);
prep1.addBatch();//add the columns that have been entered
}
conn.setAutoCommit(false);
prep1.executeBatch();
prep2.executeBatch();
conn.setAutoCommit(true);
System.out.print("Please Enter Query(One or All): ");
String q=input.next();
ResultSet rs= stat.executeQuery("select * from MedType;");
if(q.equalsIgnoreCase("all")){
while (rs.next()) {
System.out.print("All ID = " + rs.getString("ID") + " ");
System.out.println("All Description = " + rs.getString("Description"));}
}
if(q.equalsIgnoreCase("one")){
System.out.print("Enter ID: ");
}
int idNum=input.nextInt();
ResultSet oneRs = stat.executeQuery("select * from MedType Where"+ (rs.getString("ID")+"="+idNum));
if(q.equalsIgnoreCase("one")){
while (oneRs.next()) {
System.out.print("ID = " + oneRs.getString("ID") + " ");
System.out.println("Description = " + oneRs.getString("Description"));
}
}
rs.close();
oneRs.close();
conn.close();
}
}
ResultSet oneRs = stat.executeQuery("select * from MedType Where"+
(rs.getString("ID")+"="+idNum));
This is where I'm having trouble. Creating a statement that says return something from the table if its id is equal to the user input. I get this error
Exception in thread "main" java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (near "=": syntax error)
In query you are trying to access single row by passing id.. In generally sql query we are using to access single row by passing some information. select * from MedType where id=3 this query will return you result set containing row or rows with id equals to 3.
so in your code your query should be select * from MedType where id="+idNum+" if in your db id column is int.
and keep this query in if block only i.e
if(q.equalsIgnoreCase("one"))
{
System.out.print("Enter ID: ");
int idNum=input.nextInt();
ResultSet oneRs = stat.executeQuery("select * from MedType Where id="+idNum+" ");
// if id column in db is int if it is string then use id='"+idNum+"'
while (oneRs.next())
{
System.out.print("ID = " + oneRs.getString("ID") + " ");
System.out.println("Description = " + oneRs.getString("Description"));
}
}
In your query:
select * from MedType Where"+ (rs.getString("ID")+"="+idNum
you seem to try to grab the ID from the first resultset where you return all tuples.
That won't work as in the where clause the ID won't be there (as there is no result right now without rs.next()). If there was a result then you potentially have something like 'where 3 = 3' (3 would be the result of the previously returned value. Have you tried simply to use:
select * from MedType Where ID = " + idNum
Hope that makes sense.
Related
i'm inserting multiple rows into a table using a single insert statement. The table has an auto increment field as the primary key.
Like so: INSERT INTO MyTable VALUES (?,?,?,?),(?,?,?,?),(?,?,?,?),(?,?,?,?)
StringJoiner sj = new StringJoiner(",");
for(int i=0;i<salesmen.size();i++)
sj.add("(?,?,?,?)");
sql.append("INSERT INTO MyTable ");
sql.append("VALUES ");
sql.append(sj.toString());
try(PreparedStatement statement = connection.prepareStatement(sql.toString(),Statement.RETURN_GENERATED_KEYS)){
int i = 1;
for(Salesman salesman : salesmen){
statement.setDate(i++, DateUtil.toSqlDate(date));
statement.setString(i++, salesman.getName());
statement.setInt(i++, salesman.getWeeklyTargetCustomerId());
statement.setInt(i++, salesman.getCycle());
}
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
while(generatedKeys.next()) {
log.info("generated key: " + generatedKeys.getLong(1)); //only prints 1 id
}
}
catch(SQLException e){
log.info("(!!) SQL Exception in Execution: " + e.getMessage());
log.info("\n\n" + sql.toString() + "\n");
}
When i call getGeneratedKeys(), it returns a ResultSet with only the id of the last row inserted, and not all of the rows. If i insert 50 rows, how do i obtain a resultset with 50 generated keys?
Although it's an old question, I hope it helps someone.
PreparedStatement pre = connection.prepareStatement("SQL", PreparedStatement.RETURN_GENERATED_KEYS);
for(Salesman salesman: salesmen) {
pre.setString(i++, ...);
pre.setString(i++, ...);
....
pre.addBatch(); // Add this
}
pre.executeBatch(); // Add this
ResultSet rs = pre.getGeneratedKeys();
while(rs.next()) {
int id = rs.getInt(1); // This should contain the id of the inserts in order.
}
I have an issue on how to insert a value from another table into a new one. I have the following code:
Scanner scanner1 = new Scanner(System.in);
java.sql.Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM flight");
int f_id = scanner.nextInt();
int air_id = scanner.nextInt();
while (res.next()) {
if (Integer.parseInt(res.getString("air_id")) == air_id && Integer.parseInt(res.getString("f_id")) == f_id) {
if (Integer.parseInt(res.getString("f_status_f_id_s")) > 0) {
System.out.println("You can reserve");
stmt=(Statement) conn.createStatement();
stmt.execute("SET FOREIGN_KEY_CHECKS=0");
String query1= "INSERT INTO reservations" +" VALUES(1,6/6/2020,)"+air_id+"(..,..,;
stmt.executeUpdate(query1);
To be more specific on the line String query1= "INSERT INTO reservations" +" VALUES(1,6/6/2020,)"+air_id+"(..,..,; I want the air_id to be the value I scanned before such as f_id. Is this the right syntax way to do it?
Use Prepared Statements to that .i.e:
PreparedStatement stmt= con.prepareStatement();
stmt.execute("SET FOREIGN_KEY_CHECKS=0");
//put ?(no of values you need to insert)
String query1= "INSERT INTO reservations values(?,?,?)";
stmt.setInt(1,1);//1 specifies the first parameter in the query
stmt.setString(2,"6/6/2020");
stmt.setInt(3,air_id);//pass your variable
stmt.executeUpdate(query1);
You can insert the variable in your query by using the following code:
String query1= "INSERT INTO reservations" +" VALUES(1,6/6/2020,)"+air_id=#air_id+"(..,..,;
Thank you, I hope it helps you
I want to store the password for required ID using java. Everything is working fine except that I am getting this Exception
"SQL Exception thrown: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '(Pass_word) set Pass_word = 'pass' where ID = 2' at line 1".
I am getting this exception only in update query but not in select query.I am using Eclipse. Can anyone tell me what I am doing is wrong?
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class information {
public static void main(String[] args) {
String password;
ResultSet rs;
String queryString;
int x=1;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost/onlineexam","root", "batch12#nitap");
System.out.print("Database is connected !");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = null;
while(x==1)
{
System.out.println("Press 1 to enter student id");
System.out.println("Press 2 to exit");
Scanner s= new Scanner(System.in);
int choice = s.nextInt();
switch(choice)
{
case 1: System.out.println("Enter the ID of student");
int id = s.nextInt();
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID=" +id;
rs= stmt.executeQuery(queryString);
//System.out.println(rs.getInt("ID"));
while(rs.next())
{
if(rs.getInt("ID")== id)
{
String roll = rs.getString("Roll_no");
String date = rs.getString("Date");
String time = rs.getString("Time");
String c_name = rs.getString("Course_name");
String c_code = rs.getString("Course_code");
password pass1= new password(roll,date,time,c_name,c_code);
pass= pass1.passwd();
System.out.println(pass);
queryString =" Update student_reg(Pass_word) set Pass_word = 'pass' where ID = ?";
//queryString= "INSERT INTO student_reg(Password) VALUES ('password') where ID = ?";
//stmt.executeUpdate(queryString);
//PreparedStatemenet pstmt = conn.preparedStatement("INSERT INTO student_reg(Password) VALUES ('password') where ID = ?");
//pstmt.setLong(1, id);
pstmt = conn.prepareStatement(queryString);
pstmt.setInt(1, id);
int numberOfUpdatedRecords = pstmt.executeUpdate();
s.close();
}
}
break;
case 2: x=0;
}
}
if(conn!= null)
{
stmt.close();
pstmt.close();
conn.close();
conn = null;
}
}
catch(ClassNotFoundException cnf)
{
System.out.println("Driver could not be loaded: " + cnf);
}
catch(SQLException sqle)
{
System.out.println("SQL Exception thrown: " + sqle);
}
catch(Exception e)
{
System.out.print("Do not connect to DB - Error:"+e);
}
}
}
Your code has many problem:
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID= id";
This line you have condition where but you not set the value yet, you should set
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
Better if you take a look at PreparedStatement for prevent SQL Injection as well.
The last one:
queryString= "INSERT INTO student_reg(Password) VALUES ('password') where ID = id";
This line seem you want to update something. Please review it.
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID= id";
should be
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
This would fix the error, but it would be better to use a PreparedStatement, where the query String looks like "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = ?", and you pass the id as a parameter.
It is so obvious because you shouldn't include the 'id' in your query string:
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
Very good hint from #spencer: you can not use WHERE clause in your INSERT INTO statement. Probably you wanted to UPDATE a row with that id. Also it is better to do it using PreparedStatemenet to avoid such mistakes:
conn = DriverManager.getConnection("jdbc:mysql://localhost/onlineexam","root", "batch12#nitap");
PreparedStatemenet pstmt = conn.preparedStatement("UPDATE student_reg SET password = 'password' where ID = ?");
pstmt.setLong(1, id);
int numberOfUpdatedRecords = pstmt.executeUpdate();
I suggest you to rename the column name password, because it is a reserved word in mysql, so you may get strange results working with that column name. Change it to some other thing like: pass_word or passwd , ... . As you may know you can use keywords as column names in your queries using some quotes or other things but it is more safe to rename it to another name, just for hint.
if you use this connection without a connection-pool, you may want to close the Statement and the Connection.
Good Luck.
I'm trying to count the input and match it with the data field in database then count the status and display the number of books that the input had borrowed.
Statement statement = conn.createStatement();
String sql = "SELECT COUNT(jtfMemberID.getText()) as num FROM LOAN WHERE LOAN_STATUS='BORROWED'";
ResultSet rs1 = statement.executeQuery(sql);
int personCount = 0;
if(rs1.next()) {
personCount = rs1.getInt("num");
jlbBookBorrow.setText(rs1.getString(personCount));
}else{
jlbBookBorrow.setText("0");
}
The text jtfMemberID.getText() will be interpreted literally in your SQL String. You need to extract it out:
String sql = "SELECT COUNT(" + jtfMemberID.getText() + ") as num FROM LOAN WHERE LOAN_STATUS='BORROWED'";
Also, to protect against SQL Injection attacks, consider using PreparedStatement.
This question already has answers here:
java.sql.SQLException: Illegal operation on empty result set. when authenticating
(2 answers)
Closed 2 years ago.
I'm trying to build a pay desk in a grocery store and my code actually performs what I intend for it to do, but for one thing.
After I ask the user to enter how many of an item they want, the product information is gathered and works fine, but when it's supposed to ask the user to enter product-ID for next product, the line is repeated and I get the following exception in my catch: "Illegal operation on empty result set". Again, all the calculations and everything is fine except for the repeating of that line. Any ideas on what might be the problem?
The output that is repeat is like this:
Enter product (or Exit):
ERROR1: Illegal operation on empty result set.
Enter product (or Exit):
And here's the code.
try {
Class.forName("com.mysql.jdbc.Driver");
String connection = "jdbc:mysql://myDB?";
connection = connection + "user=xxx&password=xxxxxx";
Connection conn = DriverManager.getConnection(connection);
// MATA IN PRODUKTNUMMER
System.out.println("\nEnter product (or Exit):");
GroceryStore.input = GroceryStore.scan.nextLine();
PreparedStatement stmt = conn.prepareStatement(
"SELECT * "+
"FROM Products "+
"WHERE productNo = ?");
stmt.setString(1, GroceryStore.input);
ResultSet rs = stmt.executeQuery();
rs.next();
pName = rs.getString("productName");
System.out.println("Product: " + pName);
// MATA IN ANTAL
System.out.println("\nEnter amount:");
GroceryStore.amount = GroceryStore.scan.nextInt();
pPrice = rs.getDouble("productPrice");
priceRounded = new BigDecimal(pPrice).setScale(2, BigDecimal.ROUND_FLOOR);
amountRounded = new BigDecimal(GroceryStore.amount).setScale(0);
priceRounded = priceRounded.multiply(amountRounded);
GroceryStore.sum = GroceryStore.sum.add(priceRounded);
inOut.output();
inOut.input();
conn.close();
}
catch (Exception e) {
System.out.println("ERROR1: " + e.getMessage());
}
You are not checking whether your result set has any data or row in it.
ResultSet rs = stmt.executeQuery();
rs.next();
...
...
You should check whether your result is empty or having any row:
ResultSet rs = stmt.executeQuery();
if(rs.next()){
.....
your code
.....
}
You haven't checked Whether your result set is empty or not before actually retriving values from Result set...
next() returns true if there is a data in the result set, false it there is not data at the a cursor position
Place your code like this
While(rs.next())
{
pName = rs.getString("productName");
System.out.println("Product: " + pName);
// MATA IN ANTAL
System.out.println("\nEnter amount:");
GroceryStore.amount = GroceryStore.scan.nextInt();
pPrice = rs.getDouble("productPrice");
}