Using variables with JDBC - java

I want to have to use the users input for driverID, change onJob to true, if the user inputs the id.
So for example, if the user enters 1 as the driver id, the driver with id number 1 will have the onJob variable change to 1.
Here is my code currently;
public class TaxiDriver {
//String driverLocation = DRIVERFIRSTLOCATION;
//String destinationintoAPI;
//JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/DRIVER";
//Database credentials
static final String USER = "user";
static final String PASS = "password";
String driverId;
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Assign a driver to a jo...");
reader.nextInt();
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE Drivers " +
"SET OnJob = 1 WHERE id = (driverId)";
stmt.executeUpdate(sql);
// Now you can extract all the records
// to see the updated records
sql = "SELECT id, license, first, last, OnJob, Email, Telephone, Address, Postcode, Veichle FROM Drivers";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
//retrieve by column name
int id = rs.getInt("id");
int license = rs.getInt("license");
String first = rs.getString("first");
String last = rs.getString("last");
int OnJob = rs.getInt("OnJob");
String Email = rs.getString("Email");
String Telephone = rs.getString("Telephone");
String Address = rs.getString("Address");
String Postcode = rs.getString("Postcode");
String Veichle = rs.getString("Veichle");
//Display
System.out.print("ID: " + id);
System.out.print(", license: " + license);
System.out.print(", First: " + first);
System.out.print(", Last: " + last);
System.out.print(", Email; " + Email);
System.out.print(", Telephone; " + Telephone);
System.out.print(", Address; " + Address);
System.out.print(", Postcode; " + Postcode);
System.out.print(", Veichle;" + Veichle);
if (OnJob == 0) {
System.out.println(": Driver is aviliable for pickup");
} else {
System.out.println(": Driver is not aviliable for pickup");
}
}
rs.close();
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
}// do nothing
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
Right now I am getting these errors.
Connecting to a selected database...
Tue May 03 00:18:28 BST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended.
According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set.
For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'.
You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Connected database successfully...
Assign a driver to a jo...
2
Creating statement...
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'driverId' in 'where clause'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1541)
at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2605)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1469)
at TaxiDriver.main(TaxiDriver.java:71)
Goodbye!
Much thanks in advance.

First, you actually need to read in a value into driverId somewhere.
That aside, the problem is with your SQL statement. You have:
String sql = "UPDATE Drivers " +
"SET OnJob = 1 WHERE id = (driverId)";
You are telling the database to look for records where the value of the records' id column equals the value of their driverId column.
You need to get the value of your driverId variable into the SQL rather than putting the actual characters "driverId" into the SQL, where (as you see) it is interpreted as the name of a column.
Using your approach you need to do:
String sql = "UPDATE drivers SET OnJob=1 WHERE id=" + driverId;
But dynamic SQL is dangerous and you are better off using a PreparedStatement. That will sanitize the user inputs and prevent SQL injection attacks.
String sql = "UPDATE drivers SET OnJob=1 WHERE id=?";
PreparedStatement ps = connection.createPreparedStatement(sql);
ps.setInt(1, Integer.parseInt(driverId));
ResultSet rs = ps.executeQuery();

You don't seem to be setting the driverId from user input.
Update your sql statement with valid id value, before executing the script.
i.e.
int driverId = 123;// This is user input, am assuming its type int.
String sql = "UPDATE Drivers SET OnJob = 1 WHERE id =" + driverId;
//now execute your sql
String driverId = "123";//This is user input, am assuming its type String.
String sql = "UPDATE Drivers SET OnJob = 1 WHERE id =" + "'" + driverId + "'";
//now execute your sql
Edit: I highly recommend QuantumMechanic's solution of using PreparedStatement as its much safer and hides all the handling of different types.

Related

Java JDBC query not accepted

Hey I'm making a little webapp and have a java file in it with a function what connects a db and fetches the data.
But I'm getting a exception anyone knows why because my query is valid if I'm right.
I use eclipse and mysql workbench.
Function:
import java.sql.*;
public class Functions {
public void dbConn(String nVal, String inpVal){
System.out.println("Running function...");
if(nVal != null || inpVal != null){
String sqlSerch;
if(nVal.equals("name")){
sqlSerch = "ID, aNaam FROM profiles WHERE naam = 'casper'";
}else{
sqlSerch = "naam, aNaam FROM profiles WHERE ID = " + inpVal;
}
//driver / db path
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/profile";
//DB user&password
final String USER = "root";
final String PASS = "";
//declare con & sql var
Connection conn = null;
Statement stmt = null;
//register jdbc driver
try{
Class.forName(JDBC_DRIVER);
//make a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//SQL Statement
stmt = conn.createStatement();
String sql = "SELECT "+ sqlSerch;
ResultSet rs = stmt.executeQuery(sql);
//Declareer variablen met data uit db
//int id = rs.getInt("ID");
String naam = rs.getString("naam");
String aNaam = rs.getString("aNaam");
System.out.println( naam + aNaam);
rs.close();
stmt.close();
conn.close();
}catch(Exception e){
System.out.println(e);
}
System.out.println(" - " + nVal + " - " + inpVal);
}
}
}
exception:
java.sql.SQLException: Column 'naam' not found.
database structure:
Thank you in advance,
Casper
When you receive "name" through the nVal parameter, you select only ID and aNaam columns.
So, if you try to get values for naam from that ResultSet you get the Exception.
Also, I suggest limiting the results of your query to 1, since you use the WHERE clause with naam and ID, which seem to be not unique, unless there's some constraint not included in the screenshot.
Hope this helped.
You branch and create your queries:
if(nVal.equals("name")){
sqlSerch = "ID, aNaam FROM profiles WHERE naam = 'casper'";
}else{
sqlSerch = "naam, aNaam FROM profiles WHERE ID = " + inpVal;
}
Then regardless of the branch, you get your result set values:
String naam = rs.getString("naam");
String aNaam = rs.getString("aNaam");
But "naam" will not be in your "ID, aNaam" search.
In general, a good rule of thumb is to always return the same 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.

MySQLSyntaxErrorException in SQL syntax

I am trying to select data from a table using prepared statement. But it seems like I am getting syntax error which I cannot solve alone.
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String dbusername = "root";
String dbpassword = ""; // Change it to your Password
// Setup the connection with the DB
connection = DriverManager.getConnection(url, dbusername,
dbpassword);
String query = "SELECT * FROM admin WHERE username = ? AND password = ?";
try {
// connection.setAutoCommit(false);
selectUser = connection.prepareStatement(query);
selectUser.setString(1, username);
selectUser.setString(2, password);
// Execute preparedstatement
ResultSet rs = selectUser.executeQuery(query);
// Output user details and query
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: " + query);
boolean more = rs.next();
// if user does not exist set the validity variable to true
if (!more) {
System.out
.println("Sorry, you are not a registered user! Please sign up first!");
user.setValid(false);
}
// if user exists set the validity variable to true
else if (more) {
String name = rs.getString("name");
System.out.println("Welcome " + name);
user.setName(name);
user.setValid(true);
}
} catch (Exception e) {
System.out.println("Prepared Statement Error! " + e);
}
} catch (Exception e) {
System.out.println("Log in failed: An exception has occured! " + e);
} finally {
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
System.out.println("Connection closing exception occured! ");
}
connection = null;
}
return user;
}
I get following error.
Prepared Statement Error! 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 '? AND password = ?' at line 1
But I don't see any error in that code line.
Change
ResultSet rs = selectUser.executeQuery(query);
to
ResultSet rs = selectUser.executeQuery();
when you already prepared the statement in connection.prepareStatement(query); then why to pass the query again in selectUser.executeQuery(query);
what you want to do is use this method
ResultSet rs = selectUser.executeQuery();
You have already loaded your query inside the prepared statement here ,
selectUser = connection.prepareStatement(query);
so execute it by ,
ResultSet rs = selectUser.executeQuery();
Also read ,
How does PreparedStatement.executeQuery work?

How to remove this bug while making jdbc simple program

Hi
I am making simple program of getting data from data base .I download sql for mac and insert schema , then table and entry .So I need to retrieve data from data base .I am using mysql .
I also insert conector jar of mysql .
I do like that
import java.sql.*;
![public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Database";
// Database credentials
static final String USER = "";
static final String PASS = "";
public static void main(String\[\] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM Employee";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("name");
// String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
// System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample][3]
Connecting to database...
Goodbye!
java.sql.SQLException: null, message from server: "Host '192.168.1.100' is not allowed to connect to this MySQL server"
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1086)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1114)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2493)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2311)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:347)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at FirstExample.main(FirstExample.java:21)
Your DB user is not allowed to connect to your MySQL server. In MySQL (strangely) there is something like a firewall and access is defined per user per host. You need to connect to MySQL via any SQL client and give access:
http://dev.mysql.com/doc/refman/5.1/en/adding-users.html
For example a bit too broad access but should work:
GRANT ALL PRIVILEGES ON *.* TO 'monty'#'%' WITH GRANT OPTION;
If you didn't create a user first:
CREATE USER 'monty'#'localhost' IDENTIFIED BY 'some_pass';

How to change the database name and table using java?

i try to understand this part of code:
Properties details= new Properties();
details.load(new FileInputStream("details.properties"));
String userName = details.getProperty("root");
String password = details.getProperty("mysqlpassword");
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement st = conn.prepareStatement("insert into 'Email_list' values(?)");
for(String mail:mails)
i understand that test database is a default database. but if i want to use an existing database, i will just modify test to another database name isn't it?
If yes how do i modify my code if my new database is Test2 with table name Email which contains mail column with varchar(100)
i try to replace test by Test2 Email_list by Email but i don't know where to put the column name mail.
Thank you for help
The INSERT statement you use omits the columns.
INSERT INTO tablename VALUES (1, 2, 3)
can be written if the table has three columns and for all three columns values are provided.
If some columns can be left empty or have default values, you can write
INSERT INTO tablename (column1, column2) VALUES (1, 2)
In this cas the value for column3 is null or the default value.
So in your case the column name is put nowhere.
You are missing PORT number in your connection string...
String url = "jdbc:mysql://localhost/test"; should be String url = "jdbc:mysql://localhost:PORT_NUMBER/test"; like String url = "jdbc:mysql://localhost:3306/test";
Let me know if you have any queries...
Also, Check below how Prepared Statement works
import java.sql.*;
public class TwicePreparedStatement{
public static void main(String[] args) {
System.out.println("Twice use prepared statement example!\n");
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:
//localhost:3306/jdbctutorial","root","root");
try{
String sql = "SELECT * FROM movies WHERE year_made = ?";
prest = con.prepareStatement(sql);
prest.setInt(1,2002);
ResultSet rs1 = prest.executeQuery();
System.out.println("List of movies that made in year 2002");
while (rs1.next()){
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1,2003);
ResultSet rs2 = prest.executeQuery();
System.out.println("List of movies that made in year 2003");
while (rs2.next()){
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Good Luck!!!

Categories

Resources