Java JDBC query not accepted - java

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.

Related

Java JDBC throwing an error for an SQL query asking to return details from only particular rows

I have a database called 'airplane' inside which there is a table named booking.
The booking table has the columns phone(int type) ,name(text type),address(text type),city(text type) destination(text type),date(text type). I want to fetch only the rows whose phone column has value or data equal to phone number entered by the user . I wrote the following code for it . For context , I am using java using JDBC
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/airplane";
static final String USER = "root";
static final String PASS = "";
Connection conn = null;
try
{
System.out.println("enter cell no");
int cell=sc.nextInt();
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
// My SQL SELECT query.
String query = "SELECT * FROM `booking` where phone=cell";
// creating the java statement
Statement st = conn.createStatement();
/** executing the query, and getting a java resultset of all rows whose phone
column has the value equal to one entered by user and stored by me in
int variable cell**/
ResultSet rs = st.executeQuery(query);
//iterate through the java resultset
while (rs.next())
{
int Phone = rs.getInt("phone");
String Name = rs.getString("name");
String Address = rs.getString("address");
String City = rs.getString("city");
String Destination = rs.getString("destination");
String Date = rs.getString("date");
// print the results
System.out.format("%d, %s, %s, %s, %s, %s\n", Phone, Name, Address, City, Destination, Date);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
I am getting the error:
Got an exception!
Unknown column 'cell' in 'where clause'
What am I doing wrong?
Try this:
String query = "SELECT * FROM `booking` where phone=" + cell;
A better way to handle this is to use PreparedStatement
This case, the query would look like:
String query = "SELECT * FROM `booking` where phone=?"
and
statement.setInt(1, cell);
you will see it's gonna run
String query = "SELECT * FROM booking where phone="+"\"%s\"";
query=String.format(query,cell);

JAVA GUI - GET and SHOW DATA FROM MYSQL

I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.
public void findVendor() {
String vatEntered = vendorID.getText();
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
ResultSet resultSet = st.executeQuery(check);
boolean status = true;
if(resultSet.next()==status){
nameSelected.setText(resultSet.getString(1));
adressSelected.setText(resultSet.getString(2));
countrySelected.setText(resultSet.getString(3));
vatSelected.setText(resultSet.getString(4));
ptermsSelected.setText(resultSet.getString(5));
conn.close();
}
else {
JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new CreateVendor().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:
String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
But it is better to use a prepared statement instead.
String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:
String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
where resultSet.getString(1); would be data from column1.

Netbeans java application - executing query on MySql database

In the project I'm working on I need to execute Searching SQL query i.e the wildcard characters in Java Netbeans.
I'm able to execute simple queries like
String driver = "jdbc:mysql://localhost/techo";
String un = "root";
String pw = "root";
String empid = id.getText();
try{
Connection con = DriverManager.getConnection(driver,un,pw);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select*from employees where empid ="+empid+"");
while(rs.next())
{
String name = rs.getString("name");
String salary = rs.getString("salary");
name1.setText(name);
salary1.setText(salary);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
This works completely fine. But now I want to use this MySql query
Mysql>select * from employes where empid like "123%";
instead of this
Mysql>select * from employes where empid =123;
in java Netbeans.
I've tried to do this
String driver = "jdbc:mysql://localhost/techo";
String un = "root";
String pw = "root";
String empid = id.getText();
try{
Connection con = DriverManager.getConnection(driver,un,pw);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid%+"");
while(rs.next())
{
String id = rs.getString("EmpId");
String name = rs.getString("name");
String salary = rs.getString("salary");
area.setText(id +" "+name+" "+salary+" "+ "\n");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
As you can see that in the 8th line I've inserted the wildcard character(%) but this ain't working. How can I solve this?
Your wildcard character is misplaced.
It should be:
ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid+"%");
In this case the % char will be treated as a wildcard.
If you want to search the % char itself, you have to escape it following the mysql escape rules:
ResultSet rs = stm.executeQuery("select*from employees where empid like \""+empid+"%%\"");
Pay special attention to the quotes

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.

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