I get the error:
'Unknown column 'customerno' in 'field list' '.
But, that column exists in my customer table. Then why am I getting this exception ?
Code:
import java.sql.*;
public class Classy {
static String myQuery =
"SELECT customerno, name" +
"FROM customers;";
public static void main(String[]args)
{
String username = "cowboy";
String password = "1234567";
try
{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(myQuery);
while(rs.next())
{
System.out.print(rs.getString("customerno"));
}
} catch(SQLException ex){System.out.println(ex);}
}
}
Look at what your query really is. This:
static String myQuery =
"SELECT customerno, name" +
"FROM customers;";
is equivalent to:
static String myQuery = "SELECT customerno, nameFROM customers;";
Now can you see what's wrong? I'm surprised it complained about customerno rather than the lack of a FROM part...
Note that I suspect you don't want the ; either. I'd write it all one one line just for readability, when you can, as well as limiting the accessibility and making it final:
private static final String QUERY = "SELECT customerno, name FROM customers";
the problem with your syntax is that you have no space between name and FROM
String myQuery =
"SELECT customerno, name" + // problem is here
"FROM customers;";
instead add a space after name
String myQuery =
"SELECT customerno, name " + // add space here
"FROM customers";
import java.sql.*;
public class Classy {
static String myQuery =
"SELECT customerno, name" +
"FROM customers;";
public static void main(String[]args)
{
String username = "cowboy";
String password = "1234567";
try
{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(myQuery);
while(rs.next())
{
//Try and change this with the numeric value that is present in the database,
e.g if it's column 2 do something like
rs.getString(1);
System.out.print(rs.getString("customerno"));
}
}catch(SQLException ex){System.out.println(ex);}
}
}
Related
I have a music database so I'll need a search function, now when entering into the search bar, I get the error : "Invalid argument in JDBC call: parameter index out of range: 1"
public static Song getSongByName(String name)
{
String sql =
"SELECT songID FROM Song "+
"WHERE name = '?'; ";
Connection conn = Connections.getConnection();
Song erg = null;
try
{
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
rs.next();
int id = rs.getInt (1);
name = rs.getString (2);
erg = new SongImpl(id,name);
rs.close();
pstmt.close();
}
catch(SQLException exc)
{
System.err.println("Fehler: in SQL-Aufruf");
System.err.println("["+sql+"]");
exc.printStackTrace();
System.exit(6);
}
Connections.putConnection(conn);
return erg;
}
It seems like you are selecting just one column instead of two.
The correct SQL query would be:
SELECT songID, songName FROM Song WHERE name = '?';
Try this:
public static Song getSongByName(String name)
{
String sql =
"SELECT songID, songName FROM Song "+
"WHERE name = ?";
Connection conn = Connections.getConnection();
Song erg = null;
try
{
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
rs.next();
int id = rs.getInt(1);
String name = rs.getString(2);
erg = new SongImpl(id, name);
rs.close();
pstmt.close();
}
catch(SQLException exc)
{
System.err.println("Fehler: in SQL-Aufruf");
System.err.println("["+sql+"]");
exc.printStackTrace();
System.exit(6);
}
Connections.putConnection(conn);
return erg;
}
Let me know if that helped :)
Look onto examples https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Try to remove single quotes:
String sql =
"SELECT songID FROM Song "+
"WHERE name = ?; ";
You should use string parameters without quotes because your statement interpreted as a SQL query without parameters.
I have two tables named mytest and class what I need to do is to join them by the column id that exists in both table, but the problem is that I need to firstName column be parametrized in order to join the selected firstName, not all the columns that have the same id with fristName column this is the point I got but I have an error
SELECT mytest.firstName,class.name
FROM mytest
INNER JOIN class ON mytest.id=class.id
where fristName=?
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1``
public List <studentrgister> showcourse(String names) throws Exception {
List<studentrgister> students = new ArrayList<>();
String connectionURL = "jdbc:mysql://localhost:3306/web_student_tracker";
System.out.println("loding the driver");
Statement s=null;
studentrgister mystudent=null;
Connection myConn = null;
myConn= DriverManager.getConnection(connectionURL, "webstudent", "webstudent");
System.out.println("username and password is correect");
PreparedStatement myStmt=null;
ResultSet myRs = null;
String name=names;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver is loaded");
String sql="SELECT mytest.firstName,class.name FROM mytest INNER JOIN class ON mytest.id=class.id where mytest.firstName=? " ;
s =myConn.createStatement();
s.executeQuery(sql);
myRs=s.getResultSet();
if (myRs.next()) {
String classname = myRs.getString("name");
int numbername=myRs.getInt("firstName");
mystudent = new studentrgister(classname,numbername);
students.add(mystudent);
}
else {
throw new Exception("Could not find student id: " );
}
return students;
}
finally {
close(myConn,myStmt,null);
}
}
If you want to use parameters in a SQL statement, you need to use a PreparedStatement. For example:
String sql = "SELECT mytest.firstName,class.name FROM mytest "
+ "INNER JOIN class ON mytest.id=class.id "
+ "where mytest.firstName = ? " ;
PreparedStatement ps = myConn.prepareStatement(sql);
ps.setString(1, "Anne"); // we apply the parameter value
ResultSet rs = ps.executeQuery();
while (rs.next()) {
...
}
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 do I modify this code to take in PreparedStatement Objects (instead of Statement Objects)?
package com.cs330;
import javax.ws.rs.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
#Path("ws2")
public class IngredientServices
#Path("/ingredients")
#GET
#Produces("text/plain")
public String getIngredients() throws SQLException, ClassNotFoundException {
String connectStr="jdbc:mysql://localhost:3306/fooddb";
//database username
String username="root";
//database password
String password="csci330pass";
/* The driver is the Java class used for accessing
* a particular database. You must download this from
* the database vendor.
*/
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
//Creates a connection object for your database
Connection con = DriverManager.getConnection(connectStr, username, password);
/* Creates a statement object to be executed on
* the attached database.
*/
Statement stmt = con.createStatement();
/* Executes a database query and returns the results
* as a ResultSet object.
*/
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient");
/* This snippet shows how to parse a ResultSet object.
* Basically, you loop through the object sort of like
* a linkedlist, and use the getX methods to get data
* from the current row. Each time you call rs.next()
* it advances to the next row returned.
* The result variable is just used to compile all the
* data into one string.
*/
String result = "";
while (rs.next())
{
int theId = rs.getInt("id");
String theName = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId+ " , name: "+theName + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END
#Path("/ingredients/{id}")
#GET
#Produces("text/plain")
public String getIngredientById(#PathParam("id") String theId)
throws SQLException, ClassNotFoundException {
int intId = 0;
try
{
intId = Integer.parseInt(theId);
}
catch (NumberFormatException FAIL)
{
intId = 1;
}//Obtaining an ingredient from the database
String connectStr="jdbc:mysql://localhost:3306/fooddb";
String username="root";
String password="csci330pass";
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
Connection con = DriverManager.getConnection(connectStr, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient
WHERE id=" +intId);
String result = "";
while (rs.next())
{
int theId2 = rs.getInt("id");
String theName2 = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId2+ " , name: "+theName2 + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END METHOD
#Path("/ingredients/name")
#GET
#Produces("text/plain")
public String getIngredientByName(#QueryParam("name") String theName)
throws SQLException, ClassNotFoundException
{
//Obtaining an ingredient from the database
String connectStr="jdbc:mysql://localhost:3306/fooddb";
String username="root";
String password="csci330pass";
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
Connection con = DriverManager.getConnection(connectStr, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient WHERE
name='" + theName + "'");
String result = "";
while (rs.next())
{
int theId3 = rs.getInt("id");
String theName3 = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId3+ " , name: "+theName3 + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END METHOD
}//END CODE
I know for a fact that it is not as simple as just changing the object variable from Statement to PreparedStatement... That's why I'm asking for some suggestions here. Thank You.
Few steps:
Change the type from Statement to PreparedStatement.
Store your queries in String variables. Any place where you should use a dynamic value (e.g. the places where you concatenate a String) will be parameters for your query, replace these variables by ?.
Create the PreparedStatement by using Connection#prepareStatement rather than using Connection.createStatement.
Set the parameters in your PreparedStatement by using setXxx methods.
Execute the statement by using executeQuery method.
An example is covered in PreparedStatement javadoc.
This is how you can change getIngredientById method by following steps above:
Connection con = DriverManager.getConnection(connectStr, username, password);
//from "SELECT id, name, category FROM ingredient WHERE id=" + intId
//check the usage of ? instead of intId
String sql = "SELECT id, name, category FROM ingredient WHERE id = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
//setting variable in PreparedStatement
pstmt.setInt(1, intId);
ResultSet rs = pstmt.executeQuery();
String result = "";
while (rs.next()) {
//consume the data...
}
This is how you can change getIngredientByName method by following steps above:
Connection con = DriverManager.getConnection(connectStr, username, password);
//? don't need you to escape it by using ' around
//? is equals to the parameter, this is why using PreparedStatement is more safe
//it will help you to avoid SQL Injection attacks
String sql = "SELECT id, name, category FROM ingredient WHERE name = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, theName);
ResultSet rs = pstmt.executeQuery();
String result = "";
while (rs.next()) {
//consume the data...
}
Do similar for the necessary methods in your project.
I am trying to let a user lookup a football result, and the database displays that result from the database, but i keep getting this error:
Exception in thread "main" java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
This is my "useFootballBean.java" bean:
package results;
import results.*;
import java.util.*;
import java.sql.*;
public class UseFootballBean
{
public static void main(String[] args)
throws SQLException, ClassNotFoundException
{
Scanner keyboard = new Scanner(System.in);
String home;
ResultsBean resultsBean = new ResultsBean();
System.out.print("\nEnter Team: ");
home = keyboard.next();
home = resultsBean.getHome(home);
if (home.equals(null))
System.out.println(
"\n*** No such Team ***");
else
System.out.println("\nTeam " + home);
}
}
This is my "resultsBean.java" bean
package results;
import java.sql.*;
public class ResultsBean
{
private Connection connection;
private Statement statement;
private ResultSet results;
public String getHome(String enter)
throws SQLException, ClassNotFoundException
{
String query;
String team = null;
connectAndCreateStatement();
query = "SELECT * FROM Results WHERE homeTeam = "
+ enter;
results = statement.executeQuery(query);
if (results.next())
team = results.getString("homeTeam");
connection.close();
return team;
}
private void connectAndCreateStatement()
throws SQLException, ClassNotFoundException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection(
"jdbc:odbc:FootballData","","");
statement = connection.createStatement();
}
}
I think you are missing the single quotes required in where clause of query while comparing against a string value. Here you go:
where keyword_name='"+keyword_name+"'"
query = "SELECT * FROM Results WHERE homeTeam = " + '"+ enter + "'";
Since your query parameter is a string, you need to enclose it in quotes:
"SELECT * FROM Results WHERE homeTeam = '" + enter + "'";
However, this is still a bad approach, because it leaves you vulnerable to SQL injection (Remember Bobby Tables?), and will break if the user enters a team name containing quote characters (like England's Greatest Team). Therefore, you should use a PreparedStatement (see Java tutorial).
You are missing single quotation in your Sql Query
query = "SELECT * FROM Results WHERE homeTeam = '"
+ enter+"'";
OR with PreparedStatement to accept quotation
PreparedStatement stmt = null;
String sql;
ResultSet rows=null
try {
sql = "select * from Results where homeTeam=?"
stmt = theConn.prepareStatement(sql);
stmt.setString(1, "Team with ' are permitted!");
rows = stmt.executeQuery();
stmt.close();
}
catch (Exception e){
e.printStackTrace();
}
finally { if (stmt != null) {
stmt.close();
}
Thanks