How to insert a scanned value on a mySQL table? - java

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

Related

Java ResultSet Column count is always 1

I want to show the Column numbers of a table but it always shows the number 1. I have written the code below:
Class.forName(JDBC_DRIVER);
java.sql.Connection con=DriverManager.getConnection(DB_URL,USER,PASS);
try (Statement stmt = (Statement) con.createStatement()) {
String sql;
sql = "SELECT count(*) FROM information_schema.columns WHERE
table_name=\"my_b\"";
try (
ResultSet rs = stmt.executeQuery(sql)) {
int columCount = rs.getMetaData().getColumnCount();
System.out.println("Column number is: "+columCount);
}
stmt.close();
con.close();
Where is the error ?
First, you haven't needed Class.forName to load your JDBC drivers in a long time. Second, you are selecting a value but you are reading metadata. Third, when using try-with-resources you don't need explicit close calls (and your Connection should be closed in a finally, for example). Finally, use PreparedStatement and bind parameters. Like,
java.sql.Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
String query = "SELECT count(*) FROM information_schema.columns WHERE table_name=?";
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setString(1, "my_b");
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
int columCount = rs.getInt(1);
System.out.println("Column number is: " + columCount);
} else {
System.out.println("No rows");
}
}
} finally {
con.close();
}
You are not retrieving the result of the query, instead you are asking the result set metadata how many columns the result set has. And as your query only produce a single column (ie COUNT(*)), the result of ResultSetMetaData.getColumnCount() is 1, and that value is correct.
If you want to get the result of the query, you need to get it from the result set:
try (ResultSet rs = stmt.executeQuery(sql)) {
if (rs.next()) {
int columnsNumber = rs.getInt(1);
System.out.println("Column number is: "+columnsNumber );
}
}
The problem is that ResultSet.getColumnCount returns the number of columns in the query's result set, not the number of columns in a table.
If you are trying to get a count of columns on a table, the query you have is correct. You just need to retrieve the result of the query, rather than its metadata.
String sql = "SELECT count(*) FROM information_schema.columns WHERE table_name=\"my_b\"";
try (
ResultSet rs = stmt.executeQuery(sql));
rs.next();
int columCount = rs.getInt(1);
System.out.println("Column number is: " + columCount);
}
Class.forName(JDBC_DRIVER);
java.sql.Connection con=DriverManager.getConnection(DB_URL,USER,PASS);
try (Statement stmt = (Statement) con.createStatement()) {
String sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'database_name' AND table_name = 'table_name'"
try (
ResultSet rs = stmt.executeQuery(sql)) {
//int columCount = rs.getMetaData().getColumnCount();
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
System.out.println("Column number is: "+columnsNumber );
}
stmt.close();
con.close();
Try SELECT * FROM information_schema.columns WHERE table_name=\"my_b\"
Just omit the count(*) since this returns a single result, while you are looking for all columns.

Getting SQL exception in where clause while inserting data in database through java

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.

compare database column values in mysql with another String in java

I have a database with the following layout
databasename:macfast
table name:users
columns
id,
user_name,
password,
fullName
I want to retrieve all the values from the column user_name and check each values with another one string which is already retrieved from a TEXTFIELD.But I can't(NullpointerException). Please help me.
public void deleteFclty() {
PreparedStatement stmt = null;
ResultSet rs = null;
String username=removeText.getText();
String qry = "SELECT user_name From users ";
try {
stmt = (PreparedStatement) connection.prepareStatement(qry);
rs = stmt.executeQuery();
while (rs.next()) {
String check=(rs.getString("user_name"));
System.out.println(check);
if(check.equals(username)){
Util.showErrorMessageDialog("EQUAL");
}else{
Util.showErrorMessageDialog("NOT EQUAL");
}
}
}catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}
Problem is with the prepared statement (you don't put id into statement, which should be there instead of question mark).
Also I would recommend to do condition as "username.equals(check)", that can prevent null pointer exception.
"SELECT user_name From users where id=?"
This query has a parameter and you're not setting any value to it. Use PreparedStatement#setInt() or similar to set it, e.g.:
stmt.setInt(1, 1);
The problem is with PreparedStatement as you are using Question mark ? in your query for that you have to set the Id value.
String qry = "SELECT user_name From users where id=?";
stmt = (PreparedStatement) connection.prepareStatement(qry);
stmt.setInt(1,1001);
rs = stmt.executeQuery();
For your question in comment below:
List<String> values = new ArrayList();
while (rs.next()) {
values.add(0,rs.getString(<>))
}
// here do whatever you want to do...
// for example
for ( String value: values )
{
// check if value == TEXTFIELD
// if true then do something..
// else don't do anything
}

How to use user input as parameter for query?

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.

how to count with database statement by using netbeans

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.

Categories

Resources