I am getting a syntax error, but I am mostly sure I am doing everything right. Could you take a look?
String ORDER, DROP, CAR;
String Statement = "INSERT INTO WORKORDER"
+ "(ORDER, DROPOFFDATE, COMPLETIONDATE) VALUES "
+ "( ?, ?, null);";
//JOptionPane.showMessageDialog(frame, Statement, "Daisy Imports", 3);
try {
PreparedStatement PST = connection.prepareStatement(Statement);
ORDER = JOptionPane.showInputDialog("Please assign a order number for this order");
int ORDERi = Integer.parseInt(ORDER);
DROP = JOptionPane.showInputDialog("Please Enter the date the car was dropped off (YYYY-MM-DD)");
CAR = JOptionPane.showInputDialog("Enter the VIN for the car this work order is for");
PST.setInt(1, ORDERi);
PST.setString(2, DROP);
PST.execute();
Try getting rid of the semicolon at the end of your prepared statement.
Edit: The problem was that "ORDER" is a reserved word.
Related
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
I tried to insert following data to the database. but it gives me the above
this error.
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 ' ' in Line 1.
i tried several things but it is not fixing.
try{
Statement stat = Database.getStatement();
stat.executeUpdate("INSERT INTO"+" admission"+
" (a_id,sickness,recPhysicianDetails,
admittedDate,Patient_ID,Doctor_id,Doctor_id1)"+"
VALUES
('"+txt1.getText()+"',
'"+txt7.getText()+"','"+txt8.getText()+"', '"+txt6.getText()+"',
( SELECT ID FROM patient WHERE Patient_name='"+txt3.getText()+"' ),
( SELECT ID FROM employee WHERE Name='"+txt9.getText()+"' ),
( SELECT ID FROM employee WHERE Name='"+txt10.getText()+"')" );
}
catch(Exception e){
e.printStackTrace();
}
In your solution, quotation marks (') are not rightly placed, plus there is a missing closing bracket in the end. Using PreparedStatement will make sure you don't need to worry about quotation marks, try this:
Connection conn = //get connection
PreparedStatement stat = conn.prepareStatement("INSERT INTO admission (a_id,sickness,recPhysicianDetails,admittedDate,Patient_ID,Doctor_id,Doctor_id1)"
+" VALUES(?, ?, ?, ?, (SELECT ID FROM patient WHERE Patient_name = ?),(SELECT ID FROM employee WHERE Name = ?),(SELECT ID FROM employee WHERE Name = ?))");
stat.setString(1, txt1.getText());
stat.setString(2, txt7.getText());
stat.setString(3, txt8.getText());
stat.setString(4, txt6.getText());
stat.setString(5, txt3.getText());
stat.setString(6, txt9.getText());
stat.setString(7, txt10.getText());
stat.executeUpdate();
I will suggest to use prepared statement instead directly calling the value from the textbox.
try{
Statement stat = Database.getStatement();
stat.executeUpdate("INSERT INTO admission"+
"(a_id,sickness,recPhysicianDetails,admittedDate,Patient_ID,Doctor_id,Doctor_id1)"+
" VALUES('"+txt1.getText()+"','"+txt7.getText()+"','"+txt8.getText()+"','"+txt6.getText()+"',"+
"(SELECT ID FROM patient WHERE Patient_name='"+txt3.getText()+"'),"+
"(SELECT ID FROM employee WHERE Name='"+txt9.getText()+"'),"+
"(SELECT ID FROM employee WHERE Name='"+txt10.getText()+"')");
}
catch(Exception e){
e.printStackTrace();
}
You here inserted some double quotation marks in wrong places, please check it, it should work.
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 + "'";
Im trying to add the number 1 to a certain field. How could i manage to do that? Ive tried it but i can never get it to add 1. My ms access table column is set to Number not text.
if (s2.equals(box1Text)) {
if (s3.equals(box2Text)) {
if (s5.equals(currentWinner)) {
String sql = "UPDATE Table2 "+ "SET Score = ? " + "WHERE Better = '" + s1+"'";
PreparedStatement stmt = con.prepareStatement(sql);
//points made here
if (s4.equals(betScore)) {
stmt.setString(1, "+1");//how could i add 1 to the field?
stmt.executeUpdate();
} else {
}
First you do something that is regarded as bad practice : you construct your query by adding the value of a parameter in the string.
String sql = "UPDATE... >+ s1 +<..."
Please nether do that (what is between > and <) when programming seriouly, but allways use ? to pass values.
Second, SQL can do the job for you :
String sql = "UPDATE Table2 SET Score = Score + 1 WHERE Better = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, s1);
stmt.executeUpdate();
(try, catch, tests and other details omitted for brevity)
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.