I'm having an issue with my query not working. This is the command variable.
When it executes it should be retrieving the tuples that have BSc as their degree. I have tested this in oracle directly and the query returns these. It is identical to the command statement.
When I print out command, the line looks exactly the same as my command that worked in oracle.
SELECT distinct fname, lname, student_id FROM student where degree='BA';
Yet, it should be printing out to the screen. The tables are loaded into oracle already.
I've been racking my brain with this issue but can't seem to find a fix!
The error I keep getting is:
ORA-00911: invalid character
What I do is I store in degree the result from scanner which is a string. So concatenating it in the command variable shouldn't make an issue -- the query looks identical to what works in oracle.
Could it be because it wants a char instead of a string? If it does, then how would I get it to make "BSc" as a char? Concatenating chars sounds dumb.
Relevant code below:
private String getDegree() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter degree code (either BA or BSc)");
return scan.next();
}
//get the degree name
String degree = getDegree();
//get statement and execute appropriate select
Statement stmt = con.createStatement();
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "';";
System.out.println(command);
ResultSet result = stmt.executeQuery(command);
//determine number of columns
ResultSetMetaData metadata = result.getMetaData();
int columns = metadata.getColumnCount();
//print heading
System.out.println("\nFNAME LNAME STUD_ID");
System.out.println("====================================");
//loop through result and print columns
while (result.next()){
for (int i=1; i <=columns; i++){
System.out.print(result.getString(i)+spaces(15-result.getString(i).length()));
}
System.out.println();
}
`
In JDBC your SQL statement should not be terminated by semicolon.
Change
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "';";
to
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "'";
Related
I have a problem updating my table from java.
i need to check colmunID(from my table PRODUCTS) = int id(given by user input) and change thats product price in table to one given by user.
PROBLEM:
static void x(int Userid, int Userprice) {
..........................................
String sql = "UPDATE Product set Price = Userprice where ID=Userid; ";
....}
I get error that i don't have column Userprice or Userid in my database. I don't know how to write this to check int User id which is given as argument in this method and not column in my database table which does not exists.
Assuming that you have both the columns with Integer datatype in DB,
String sql = "UPDATE Product set Price="+Userprice+" where ID="+Userid;
You are not passing the actual values to it and the extra ';' is not required. Also, I suggest you to prefer prepared statements, rather than above approach
While you definitely in production code want to use prepared statements to prevent sql injection, an easy fix would be the below.
String sql = String.format("UPDATE Product set Price = %d where ID=%d ",Userprice,Userid);
String wont evaluate variables in itself.
If the table for Userid does not exist in your database, you will not be able to use this in your SQL query. There are two options for you:
1. Pass the Userid and Userprice as a variables to the SQL query
String sql = "UPDATE Product set Price = " + Userprice + "where ID=" + Userid+ "; "
Or
2. Create the table in the database and join on that
String sql = "Update A Set A.Price = b.Userprice FROM Product as A INNER JOIN User as b on A.Userid = b.ID;"
PreparedStatement ps = null;
Connection con = null;
try {
con = getConnection();
String sql = "UPDATE Product set Price = ? where ID= ? ";
ps = con.prepareStatement(sql);
ps.setString(1, Userprice);
ps.setString(2, Userid);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Product Updated");
} else {
System.out.println("Error Occured");
}
I think this is something you are looking for... The query should not contain ';' in the String for your code
I am writing code in Java and I want to take every time I run this code the next line from a MySQL table.The second time I run this code is this.
String timh1 = "1";
String timh2 = "2";
PreparedStatement st = null;
String sqlGrammes = "SELECT SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE LIMIT ?,? ";
try {
st = connection.prepareStatement(sqlGrammes);
st.setString(1, timh1);
st.setString(2, timh2);
But it shows me this 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 ''1','2'' at line 1
limit accepts integer parameters, so you should use ints, not Strings:
int timh1 = 1;
int timh2 = 2;
PreparedStatement st = null;
String sqlGrammes = "SELECT SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE LIMIT ?,? ";
try {
st = connection.prepareStatement(sqlGrammes);
st.setInt(1, timh1); // notice the setInt
st.setInt(2, timh2); // here too
I was able to do it without prepared statement
int i = 0;
int j = 1;
sql = "Select SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE limit "+i+ ","+j;
got first row as output.
I am writing a code in Java where user can type a last name in a JTextField named lastname and then search for possible match in MySQL database. Say for example, user begins to type letter "M" (case insensitive and without double quotes), all the last name that starts with letter "M*" will display on JTable. If user types a second letter, say for example "A", the results on JTable will only display last names with "MA", then if user types third letter, say for example "N", JTable will only display all the last names with "MAN***" and so on..
I have read about
SELECT * FROM table WHERE lastname LIKE value
and tried to use it on my program, however, I am getting an error.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxError.Exception: 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 '%' at line 1
Here's my partial code in event when there's key pressed in JTextField lastname:
private void lastNameKeyPressed(java.awt.event.KeyEvent evt) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "students_dbs";
Statement stmt = null;
ResultSet result = null;
String driver = "com.mysql.jdbc.Driver";
String databaseUserName = "user1";
String databasePassword = "test";
PreparedStatement pst = null;
try{
conn = DriverManager.getConnection(url + dbName, databaseUserName, databasePassword);
stmt = conn.createStatement();
System.out.println("Connected to the database.");
}catch(Exception e){
System.out.println("Failed to connect ot the database.");
}
try{
String sql = "SELECT studentno, lastname, firstname, middlename FROM student WHERE lastname LIKE '%" + lastname.getText() + "'%";
pst = conn.prepareStatement(sql);
result = pst.executeQuery();
studentsTable.setModel(DbUtils.resultSetToTableModel(result));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
I googled it for a day or two now, however, I am stuck. I'm kinda new in using LIKE in MySQL. Any kind help is very much appreciated! Thank you in advance!
The position of the last ' char is wrong:
String sql = "SELECT studentno, lastname, firstname, middlename FROM student
WHERE lastname LIKE '% " + lastname.getText() + " '% ";
should be:
String sql = "SELECT studentno, lastname, firstname, middlename FROM student
WHERE lastname LIKE '% " + lastname.getText() + " %' ";
Try this:
String SQL="Select name from tablename where like %";
pst = conn.prepareStatement(sql);
pst.setString(1, txnam.gettext()+"%");
put one textfield for u to type
String sql = "SELECT studentno, lastname, firstname, middlename FROM student
WHERE lastname=?";
pst = conn.prepareStatement(sql);
pst.setString(1,jTextField1.getText());
result = pst.executeQuery();
you can use this code :
this is sql code
and then rename youre Jtabble, Like model in picture one. then call method in here initcomponent(){selectDataTable(""); }. then make event key released in youre textfield, and then write this in the event selectDatatable(textfield.gettext()); Done
Statement stmt = null;
String query = "SELECT CarLot.CAR.Make, CarLot.CAR.Model, CarLot.CAR.Year, CarLot.CAR.Sold_Status, CarLot.OWNER.First_Name,CarLot.OWNER.Last_Name"+
"FROM CarLot.CAR, CarLot.OWNER" +
" WHERE CarLot.CAR.Sold_Status = TRUE";
try {
con = getConnection();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
String heading1 = " Make"; String heading2 = " Model"; String
heading3 = " Year"; String heading4="Sold Status";
System.out.printf("%-20s %-20s %-20s %-20s\n", heading1, heading2,
heading3,heading4);
System.out.println("--------------------------------------------------------------------------\n");
while (rs.next()) {
String make = rs.getString("car.Make");
String model = rs.getString("car.Model");
int carYear = rs.getInt("car.Year");
boolean soldStatus = rs.getBoolean("car.Sold_Status");
String firstName = rs.getString("owner.First_Name");
System.out.printf("%-2s %-20s %-20s %-20s %-20s\n",
make, model, carYear,soldStatus,firstName);
}
System.out.println("\n\n");
} finally {
stmt.close();
}
The problem that I am having is a SQL syntax error, the syntax works in MySql workbench 6.0 but wont work in my Java App through JDBC, Im new to SQl and JDBC, I realize my result set may not be 100% for this query and that also may be the problem, its from a shared method, im more concerned with the SQL query statement in this case.
The problem is you are missing a space between the last selected column name and FROM. To paraphrase your query, you have:
String query = "SELECT ..., CarLot.OWNER.Last_Name"+ // oops, no space!
"FROM CarLot.CAR, CarLot.OWNER" +
" WHERE CarLot.CAR.Sold_Status = TRUE";
This error is very common, because it's hard to see a missing space at the end of a line, but there is a code style that I use to combat this - I put spaces at the start of the line, like this:
String query = "SELECT CarLot.CAR.Make, CarLot.CAR.Model, CarLot.CAR.Year, CarLot.CAR.Sold_Status, CarLot.OWNER.First_Name,CarLot.OWNER.Last_Name"+
" FROM CarLot.CAR, CarLot.OWNER" +
" WHERE CarLot.CAR.Sold_Status = TRUE";
Every line starts with quote-space, ie " ..., so now it's really obvious when a line-broken string is missing a space, and further because SQL is (generally) whitespace insensitive, you can put spaces at the end too without causing any problems.
Add a space before the FROM clause
String query = "SELECT CarLot.CAR.Make, CarLot.CAR.Model, CarLot.CAR.Year, CarLot.CAR.Sold_Status, CarLot.OWNER.First_Name,CarLot.OWNER.Last_Name" +
" FROM CarLot.CAR, CarLot.OWNER" +
" WHERE CarLot.CAR.Sold_Status = TRUE";
Aside: Consider using PreparedStatement to protect against SQL injection attacks
The first and second lines of your query don't have a space between them, so you have select ... CarLot.OWNER.Last_NameFROM CarLot... . Add the space and see what happens.
Scanner input = new Scanner(System.in);
System.out.println("Enter Staff Name: ");
String staffName = input.nextLine();
System.out.println("Enter Department Name: ");
String department =Input.nextLine();
stmt.executeUpdate("insert into staff (StaffName,department) " + "values " +
staffName,department);
This gives me an error and asks me to check the SQL manual.Is it even possible?
It is possible, since it happened. Strings must be enclosed in quotes in SQL:
insert into foo (bar, baz) values ('hello', 'world');
Learn to use prepared statements instead of string concatenations, to make your queries work, and not be subject to SQL injection attacks:
PreparedStatement stmt = connection.prepareStatement("insert into staff (StaffName, department) values (?, ?)");
stmt.setString(1, staffName);
stmt.setString(2, department);
stmt.executeUpdate();
Using the above, you don't need to mess with quotes nor escape them inside the strings.
It's not necessarily the user input being formatted incorrectly. The INSERT into should be formatted like:
INSERT INTO <table_name>
VALUES (<1>, <2>, ... <n>);
To format your SQL query correctly, you could try:
String sql = "INSTERT INTO STAFF (StaffName, department) VALUES (\'" +
staffName + "\', \'" + department + "\');";