inserting reservation to database - mysql

This has been driving me crazy and I'm sure it's something simple. I'm getting a 'values must contain at least one element' error from server when I try to input a reservation from the table that comes up. It's all running ok. No matter if I use quotes in the VALUES section or plus(+)symbols or quotes over the separating commas I get different error messages. When I put quotes over table_num I get and error telling me that you cant insert CHAR into INTEGER. When I remove quotes I get error telling me -
Severe: java.sql.SQLSyntaxErrorException: Column 'TABLE_NUM' is either not in any table in the FROM list or appears within a join specification etc. Could anyone tell me what is going on? Here's the jsp code. Thanks in advance.
<%
int tableNum = 0;
String firstName = null;
String lastName = null;
String Address = null;
int Phone = 0;
java.sql.Date date = null;
int People = 0;
if (request.getParameter("table_num")!=null){
tableNum = Integer.parseInt(request.getParameter("table_num"));
}
if (request.getParameter("first")!=null){
firstName = request.getParameter("first");
}
if (request.getParameter("last")!=null){
lastName = request.getParameter("last");
}
if (request.getParameter("address")!=null){
Address = request.getParameter("address");
}
if (request.getParameter("phone")!=null){
Phone = Integer.parseInt(request.getParameter("phone"));
}
if (request.getParameter("date")!=null){
java.util.Date utilDate = new java.util.Date(request.getParameter("date"));
date = new java.sql.Date(utilDate.getTime());
}
if (request.getParameter("people")!=null){
People = Integer.parseInt(request.getParameter("people"));
}
if(tableNum != 0 && firstName != null && lastName != null && Address != null && Phone != 0 && date != null && People != 0){
String URL = "jdbc:derby://localhost:1527/Reservations";
String USERNAME= "johnpaul";
String PASSWORD= "purlease";
Connection myCon = null;
Statement ste = null;
PreparedStatement preparedStmt = null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Connecting to DB...");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Reservations","johnpaul", "purlease");
System.out.println("Connected successfuly");
System.out.println("Inserting records into table");
Statement st = con.createStatement();
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS(TABLE_NUM,FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE,DATE,NUMBER_IN_PARTY)VALUES(table_num,first,last,address,phone,date,people)";
st.executeUpdate (query);
System.out.println("Records inserted");
}catch(SQLException se){
se.printStackTrace();
}catch(ClassNotFoundException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
%>

Your problem appears to be here:
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (table_num, first,last,address,phone,date,people)";
Two things here:
1. Escape your strings; and
2. Concatenate the values in your variables to the string.
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (" + table_num + ", '" + first + "', '" + last + "', '" + address + "', " + phone + " , '" + date + "', " + people + ");";
You may have to verify the format that your database engine expects the date field.

Related

You have an error in your SQL syntax (...) near ;

I got this message, and I couldn't find any error:
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 'where id ='null'' at line 1
I assumed this code was wrong, but it turned out it isn't.
ResultSet rs = stmt.executeQuery("select password" +
"from userinfo where id = '" + id + "';");
This is full code of error file.
private boolean checkLoginInfo(String id, String password) throws ServletException
{
Connection conn = null;
Statement stmt = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/webdb", "root", "1234");
if (conn == null)
throw new Exception("can't connect to database.<BR>");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select password" +
" from userinfo where id = '" + id + "';");
if (!rs.next())
return false;
String correctPassword = rs.getString("password");
if (password.equals(correctPassword))
return true;
else
return false;
}
There is a missing space between password and from:
select password" + "from userinfo where id = '" + id + "';"
Try this:
"SELECT password FROM `userinfo` WHERE id = '"+id+"'"
You should furthermore read about:
Escaping SQL queries
Authentication/Authorization (why do you select the password only?)
Code formatting
Edit 1:
The error messages tells us, you are setting the id to 'null' (String, because of ''), not NULL. If your id is expecting an Integer, but you are providing a String, it will break.

I want to count a column in mysql and place the results in a textfield

I have a mysql data base with a column called MemType this column will have whether a member is active. Not all members are active. I want to count the active members and display the result in a textField. I can do the count but don't know how the result comes back. My code folows:
#FXML
private void CountActionPerformed(ActionEvent event) {
String user = "root";
String password = "";
String ResultSet = null; // This is to ensure that ResultSet is empty.
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/club", user, password);
System.out.println("Connection Successful ");
// Create statement.
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT COUNT(MemType)\n "
+ "FROM members \n "
+ "WHERE MemType = 'Active ' ");
while (myRs.next()) {
CountRel.setText(myRs.getString("MemType"));
}
} catch (Exception e) {
}
}
You can give the column an alias like this:
ResultSet myRs = myStmt.executeQuery("SELECT COUNT(MemType) as MemType "
+ "FROM members "
+ "WHERE MemType = 'Active ' ");
This should be all the changes you need and you will have only one result (The count of all the Active rows)
The result is a table with a single column and a single row. You can retrieve the result using the column index:
try {
try (Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/club", user, password)) {
System.out.println("Connection Successful ");
// Create statement.
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT COUNT(*) "
+ "FROM members "
+ "WHERE MemType = 'Active '");
if (myRs.next()) {
CountRel.setText(Integer.toString(myRs.getInt(1)));
} else {
throw new Exception("error while counting");
}
}
} catch (Exception e) {
}

Matching on empty strings, not nulls, in a MySQL column

I can't get the right syntax - I'm trying to match on the column as an empty string, not a null. I've tried delimiting the string all number of ways, using single double quotes.
containerRefNo = "\"\"";
ps = getConnection().prepareStatement(
"delete from inumber_join where container_no = ?");
The error I receive is
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 'from inumber_join where container_no = '""''
When using a parameterized query you don't need to include any delimiters in the parameter value. Simply using ps.setString(1, ""); works fine for me.
That is, ...
// setup
try (Statement st = conn.createStatement()) {
st.executeUpdate(
"CREATE TEMPORARY TABLE inumber_join_temp (" +
"id INT AUTO_INCREMENT, " +
"container_no VARCHAR(10) NULL, " +
"PRIMARY KEY (id)" +
")");
st.executeUpdate(
"INSERT INTO inumber_join_temp (container_no) " +
"VALUES (null), (''), (null), (''), (null)");
}
// test
String sql =
"SELECT COUNT(*) AS n " +
"FROM inumber_join_temp " +
"WHERE container_no = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, ""); // search for empty string
try (ResultSet rs = ps.executeQuery()) {
rs.next();
System.out.println(rs.getInt(1));
}
}
... returns
2

How to insert data to a sqlite database with table name as variable

I would like to insert data into my sqlite data base but with a variable as the name of the table where the data should be entered.
try {
Random rand = new Random();
uniqueID = rand.nextInt(9998) + 1; //Generates a random number from 1 - 9999 inclusively
String dateStart = day1.getText() + "/" + month1.getText() + "/" + year1.getText();
String dateEnd = day2.getText() + "/" + month2.getText() + "/" + year2.getText();
String projectN = projectName.getText();
String addr = address.getText();
//String engineerN = engineerName.getText();
//String engineerP = engineerPassword.getText();
Class.forName("org.sqlite.JDBC");
conn2.setAutoCommit(false);
PreparedStatement ps = conn2.prepareStatement("insert into "My table name" (uniqueid,name,address,startingdate,estcompletion) values(?,?,?,?,?,?)");
ps.setInt(1, uniqueID);
ps.setString(2, projectN);
ps.setString(3, addr);
ps.setString(4, dateStart);
ps.setString(5, dateEnd);
//ps.setString(6, engineerN);
ps.execute();
ps.close();
conn2.commit();
conn2.close();
}
catch ( Exception e1) {
System.err.println( e1.getClass().getName() + ": " + e1.getMessage() );
System.exit(0);
}
}
}
public String JJI() {
return projectName.getText();
}
}
"My table name" in the prepared statement is the place where I want to put my table name getting it from projectName.getText(); at the end. The user enters projectname.getText in another class.
Thank you for the help!
Store your table name in a String variable (how you like): String tableName = "users";
Make a query variable that contains your SQL query:
String query = "insert into '" + tableName + "' (uniqueid,name,address,startingdate,estcompletion) values(?,?,?,?,?,?)";
If you would like to have variables to insert, replace the "?" with your variable names as you have done in your code:
ps.setInt(1, uniqueID);
ps.setString(2, projectN);
ps.setString(3, addr);
ps.setString(4, dateStart);
ps.setString(5, dateEnd);
Execute the query:
PreparedStatement ps = conn2.prepareStatement(query);
ps.execute();

JDBC4/MySQL syntax error: when retrieving data from mysql table

Is there anything wrong in the code below?
String sql = "SELECT username, password FROM REGCUSTOMERS" + "WHERE username = ? AND password = ?";
I'm trying to get the data from the username and password column of REGCUSTOMERS table.
Eclipse 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
private boolean isAuthenticated(String userid, String password) {
// JDBC logic to verify from database.
try {
Class.forName(driverName);
Connection conn = null;
PreparedStatement st = null;
String sql = "SELECT username, password FROM REGCUSTOMERS" + "WHERE username = ? AND password = ?";
conn = DriverManager.getConnection(databaseURL, USERNAME, PASSWORD);
st = conn.prepareStatement(sql);
ResultSet rs = st.executeQuery(sql);
if (rs.getString("username") != userid && rs.getString("password") != password) {
return false;
}
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
You have no space between REGCUSTOMERS and WHERE. Add the space and you should be fine:
String sql = "SELECT username, password FROM REGCUSTOMERS " + "WHERE username = ? AND password = ?";
This part:
... FROM REGCUSTOMERS" + "WHERE username ...
Will result in the following SQL:
FROM REGCUSTOMERSWHERE
That of course is wrong.
The + doesn't make sense there, but if you want it, you need a space at least on one side
"... FROM REGCUSTOMERS " + "WHERE username ..."