So I am trying to create a application that simulates a online video store. I have created a database on Workbench and I am trying to create a if statement that checks if the user input matches those on the emails and passwords on the database. But I either get a error about the connection or about the driver. Hoping someone can help me out, thanks!
Here is the Java code
public static void main(String[] args) throws SQLException, ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Scanner input = new Scanner(System.in);
String answer = "";
String sql = "";
String email = "";
String password = "";
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull [root on Default schema]", "<username>", "<password>");
Statement myStmt = myConn.prepareStatement(sql);
ResultSet rs;
while(!answer.equals("n") || !answer.equals("y") )
{
System.out.print("Do you have an account? (Y/N) : ");
answer = input.nextLine();
if(answer.toLowerCase().equals("n"))
{
System.out.println("Please enter the email and password for your new account.");
System.out.print("Email: ");
email = input.nextLine();
System.out.print("Password: ");
password = input.nextLine();
sql = "insert into accounts "
+ " (UserEmail, UserPassword)" + " values (?, ?)";
myStmt.executeUpdate(sql);
}
else if(answer.toLowerCase().equals("y"))
{
System.out.print("\nEmail: ");
email = input.nextLine();
System.out.print("\nPassword:");
password = input.nextLine();
rs = myStmt.executeQuery(sql);
if(!rs.absolute(1))
{
System.out.println("You do not have an account. Please create one.");
continue;
}
}
else{
System.out.println("Invalid input. Please try again.");
continue;
}
}
Here is my SQL script
create database users;
use users;
create Table Accounts(
UserEamil Char(20) NOT NULL ,
UserPassword Char(20) NOT NULL
);
Here is my error:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
This code is not going to work as the values have not been set
sql = "insert into accounts "
+ " (UserEmail, UserPassword)" + " values (?, ?)";
myStmt.executeUpdate(sql);
what you should do is create a PreparedStatement using the sql and then call setString for each paramater like
sql = "insert into accounts "
+ " (UserEmail, UserPassword)" + " values (?, ?)";
Statement myStmt = myConn.prepareStatement(sql);
myStmt.setString (1, email);
myStmt.setString (2, password);
myStmt.executeUpdate ();
note
Currently at the top of your code you have
Connection myConn = DriverManager.getConnection("....");
Statement myStmt = myConn.prepareStatement(sql);
but the value of sql at this time is an empty string - it will not work
note2
Consult this answer for how to set your connection String correctly
Have you downloaded the mysql jdbc driver?
You should be able to fix it by adding the classpath:
C:\test>java -cp c:\test\mysql-connector-java-5.1.8-bin.jar;c:\test JDBCExample
Taken from:
https://www.mkyong.com/jdbc/how-to-connect-to-mysql-with-jdbc-driver-java/
Related
I am new to java and am trying to get used to the syntax and pushing data to a MySQL table. I am having this problem and can't figure what I have done wrong. When executing my update command it gives the following error.
java.sql.SQLSyntaxErrorException: 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 ''occupation' = 'cat' WHERE first_name = 'kevin' AND last_name = 'hudgens'' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
at Driver.updateContact(Driver.java:172)
at Main.main(Main.java:119)
main file
System.out.println("Please enter the first name of the contact you want to update.");
first_name = input.nextLine();
System.out.println("Please enter the last name of the contact you want to update.");
last_name = input.nextLine();
System.out.println("Are you sure you want to update " + first_name + " " + last_name
+ "'s information. YES or NO");
String verifyUpdate = input.nextLine();
// lower for comparison
// verifyUpdate = verifyUpdate.toLowerCase();
if (verifyUpdate.equals("YES")) {
break;
} else if (verifyUpdate.equals("NO")) {
System.out.println(
"Please enter the correct first and last name of the contact you would like to update");
} else {
System.out.println("You didnt enter the correct answer. YES or NO");
}
}
// inform user what they can update
System.out.println("What would you like to update? Options are:"
+ "\nFIRST NAME \n LAST NAME \n PHONE NUMBER \n EMAIL \n OCCUPATION");
// Collect the choices
String updateColumnChoice = input.nextLine();
System.out.println("What would you like to update it to? ");
String updatedValue = input.nextLine();
driver.updateContact(first_name, last_name, updateColumnChoice, updatedValue);
here is the prepared statement
public static void updateContact(String first_name, String last_name, String updatedColumn,
String toBeUpdatedValue) {
try {
// Get connection to database
Connection myConn = DriverManager.getConnection(info);
// Create sql command for deleting
String query = "UPDATE contacts SET ? = '?' WHERE first_name = '?' AND last_name = '?' ";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, updatedColumn);
preparedStmt.setString(2, toBeUpdatedValue);
preparedStmt.setString(3, first_name);
preparedStmt.setString(4, last_name);
// push prepared statement to the database
preparedStmt.executeUpdate();
// close the connection to the database
myConn.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
Any help on this would be greatly appreciated. Along with any general criticism on my code.
As far as I know, you can use PreparedStatement's parameters only for values, not for metadata. If you need updatedColumn to be dynamic, you can do this:
String query = "UPDATE contacts SET " + updatedColumn + " = '?' WHERE first_name = '?' AND last_name = '?' ";
Note that you will have to make sure that updatedColumn is properly quoted/escaped, especially if it's coming from user data (i.e. SQL injection attack).
I'm trying to input my details in MySQL using Java.
But I keep on having following error:
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
Here is my code:
Vehicle vehicle = new Vehicle();
int vType;
System.out.println("Please enter Vehicle Type\n1 = Car\n2 = Van\n3 = Motorbike\n4 = Motorbike");
vType = input.nextInt();
if (vType==1){
System.out.println("Car Brand: ");
vehicle.setvBrand(input.next());
System.out.println("Car License Plate: ");
vehicle.setvLicense(input.next());
try {
Connection dbConn = DriverManager.getConnection(url,user,pass);
String parkCar = "INSERT INTO car_park_details(vehicle_brand, vehicle_license) values( ?, ?)";
PreparedStatement park = dbConn.prepareStatement(parkCar);
park.executeUpdate(parkCar);
park.setString(2,vehicle.getvBrand());
park.setString(3, vehicle.getvLicense());
park.execute();
System.out.println("Try daw check sa DB MYONG!");
}
catch (Exception ex){
System.out.println("Error" + ex);
}
}
Am I doing it wrong? I'm a begginer Java Developer. thanks for the help.
PreparedStatement park = dbConn.prepareStatement(parkCar);
park.setString(1, vehicle.getvBrand());
park.setString(2, vehicle.getvLicense());
park.executeUpdate();
PreparedStatement set parameters index starts from 1.
Try as below, i.e run executeUpdate() without parameters and only after you have set your parameters to the PreparedStatement:
PreparedStatement park = dbConn.prepareStatement(parkCar);
park.setString(1,vehicle.getvBrand());
park.setString(2, vehicle.getvLicense());
park.executeUpdate();
basically i have a web app in java ee with MySql DB, in my MySQl i have an ID column which is unique. now if user inputed an ID that already exist in there it pops Duplicate entry 'UserID' for key 'UID_UNIQUE', i found that error code 612 is for Duplicate name in mysql. so my question is how to get the Mysql error code and how can i pass the user that ID has already been taken
here is my java code for inserting user info to my db
public void getData(String FName,String LName,
HttpServletRequest request, HttpServletResponse response){
PrintWriter out = null;
try{
int affectedRows;
out = response.getWriter();
String query = "INSERT INTO `duckdb`.`userstb` (`UFN`, `ULN`, `UID`) VALUES ('"+FName+"', '"+LName+"', '"+Uname+"')";
affectedRows = st.executeUpdate(query);
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
}catch(Exception ex){
System.out.println(ex);
}
}
You should catch SQLIntegrityViolationException, not just Exception. That's what it's for.
You certainly should not just parse the error message. It could be in another language for example.
At the very least you should catch SQLException and examine the SQL error code, although that will be vendor-specific.
usually we use next() . with (while or if ) to clause and use the Java side to simply check if this query returned any results:
such as :
Connection con = DatabaseConnection.getConnection();
PreparedStatement ps =
con.prepareStatement
("SELECT questid FROM completedQuests WHERE characterid = ? AND questid = ?");
ps.setInt (1, characterId);
ps.setInt (2, questId);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
// Quest already completed
} else {
// Quest not completed yet
}
not exactly the way i expected but it solved my problem, thought somebody else could use it too.
System.out.println(ex);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String error = sw.toString();
if(error.indexOf("Duplicate Entry") != -1)
out.print(error);
System.out.println("PW: " + error);
brother I'm trying to help here . See I always do that validation with php,java ..etc , I will explain it very clear . You just need to write a query that (" Select * from userstb where FName = ' " + FName +" ' ") check if returns a value that means the FName already exist if not that means it's OK to register that . here completely simple example
Statement stmt = con.createStatement();
String SQL = "SELECT * From tableName WHERE FName = ' "+FName+" ' ";
ResultSet rs = stmt.executeQuery(SQL);
if(rs.next()){
System.out.println("the Name is already registered in DB ");
}else
{
//write the query to register the name
}
}
My current program can write data records in the database (also check if the primary key already exists). On the second step I want to extend my program with the feature that you are able to update/delete a dataset. UserID is the primary key. First name, Surname, Street aren't. But my aim is that you can also search for the first name or other fields, which arent primary, and get all dataset's where e.g. first name = searched value.
How I image it:
System.out.println("You have choosen edit/delete dataset!");
System.out.println("Enter UserID or other informations");
// Read in all available information from the user
//
UserInfo search = new UserInfo();
searchResult = search.getUserInfo(userid, firstname, secondname...);
The output on screen should like the following (Searched for Smith):
(1) ID0001 | Max | Smith | ....
(2) ID0002 | Justin | Smith | ...
And the user is able to choose the datset by input 1,2... which he want's to update or delete.
Problems which I dont know how to solve:
When the user haven't entered all information and just searched for eg. surname, how I can transmit the other empty fields, because the method expect also the other parameters.
When searchResult is an array, i haven't any reference to the database anymore, how I return the result back, without losing the reference to the database, that im still able to access on record.
EDIT: Using JDBC to connect to the database.
Use Scanner to get the user input, and search using this input:
System.out.println("You have choosen edit/delete dataset!");
System.out.println("Enter UserID or other informations");
Scanner scanner = new Scanner(System.in);
String searchKeyWord=scanner.next();
And then search using this keyword, or if you want to have many keywords you can use an array:
Scanner scanner = new Scanner(System.in);
String searchInput=scanner.next();
String[] keywords=searchInput.split(" ");
And then you can manage these keywords in your search like you want.
EDIT:
You can change your method so it will expect an array of keywords as an input, and whatever this array contains you will search using these keywords.
EDIT 2:
If he skips a value you can set it to null, and in your search method you only use the values that aren't null.
This is how your search method can be written to take all the parameters, and there you have to test all the cases whrer some fields can be null:
public void searchInfo(String[] keywords){
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "SELECT * FROM my_Table ";
if(keywords[0]!= null || keywords[1]!= null || keywords[2]!= null){
sql+=" WHERE ";
if(keywords[0]!= null){
sql+=" id= ?";
stmt.setInt(1, Integer.parseInt(keywords[0]));
if(keywords[1]!= null){
sql+="AND firstname= ? ";
stmt.setString(1, keywords[1]);
if(keywords[2]!= null){
sql+="AND secondname= ? ";
stmt.setString(2, keywords[2]);
}
}else if(keywords[2]!= null){
sql+="AND secondname= ? ";
stmt.setString(1, keywords[2]);
}
}else if(keywords[1]!= null){
sql+=" firstname= ? ";
stmt.setString(1, keywords[1]);
if(keywords[2]!= null){
sql+="AND secondname= ? ";
stmt.setString(2, keywords[2]);
}
}else if(keywords[2]!= null){
sql+=" secondname= ? ";
stmt.setString(1, keywords[2]);
}
}
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String first = rs.getString("firstname");
String second = rs.getString("secondname");
//Display values
System.out.print("ID: " + id);
System.out.print(", Firstname: " + first);
System.out.print(", Secondname: " + second);
}
rs.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}//end try
}
EDIT 3:
//Let's say you got a list of User object List<User> ls
Iterator<User> it= ls.iterator();
int i=1;
while(it.hasnext()){
User u= (User) it.next();
System.out.println("("+i+") : ID= "+u.getId()+" Firstname= "+u.getFirstName()+" Secondname= "+ u.getSecondName);
i++;
}
System.out.println("Please enter the index of the wanted result:");
Scanner scan = new Scanner(System.in);
int index=scan.nextInt()-1; //index in list count from 0
if(index<=ls.size()){
System.out.println("the expected result is:");
System.out.println("ID= "+ls.get(index).getId()+" Firstname= "+ls.get(index).getFirstName()+" Secondname= "+ ls.get(index).getSecondName);
}
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