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);
}
Related
now user come to my program and enter the name of any value,then i want to show the value.
System.out.println("enter name of item you want to order");
String userOrder = br.readLine();
Connection con = ConnectionToDB.connection();
String itemName= "select itemName from items";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(itemName);
while(rs.next())
{
if (rs.getString("itemName").equals(userOrder))
{
System.out.println(rs.getString("itemName"));
}
else
{
System.out.println("you order wrong item that not present");
}
}
when user enter 1st value that present in table that execute well and show the first values but when user input any other value that present in database but rs.next() is not working and else part executed. How can I overcome this?
Why you dont simply use:
"select itemName from items WHERE itemName = " + userOrder
This way you dont need iterate the result set you just:
if (rs.next()){
//Found
}
else {
//Not Found
}
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/
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
}
}
I have trouble getting my frontend to return a JOptionPane saying the ID does not exist if the user queries an ID that does not exist in my SQLite database and display the records for the ID if it exists. I tried isEmpty() which is apparently incorrect.
My code:
String SelectRecords = "SELECT * FROM Student WHERE ID_Num = ?";
String ID_Number = id_input.getText();
PreparedStatement ps = c.prepareStatement(SelectRecords);
ps.setString(1, ID_Number);
ResultSet rs = ps.executeQuery();
while(rs.next()){
String IDNum = rs.getString("ID_Num");
String LastName = rs.getString("Stud_Name_Last");
String FirstName = rs.getString("Stud_Name_First");
String DaysPresent = rs.getString("days_present");
String DaysAbsent = rs.getString("days_absent");
String DropStatus = rs.getString("drop_status");
String Course = rs.getString("course");
String LastAttended = rs.getString("last_attended_class");
String StudentRecords = "ID Number: "+IDNum+"\n"+"Last Name"+LastName+"\n"+"First Name: "+FirstName+"\n"+"Days Present: "+DaysPresent+"\n"+"Days Absent: "+DaysAbsent+"\n"+"Drop Status: "+DropStatus+"\n"+"Course: "+Course+"\n"+"Last Attended On: "+LastAttended;
Output_Label.setText(LastName+", "+FirstName+"(Retrieving...)");
if(rs.next() == true){
JOptionPane.showMessageDialog(null, StudentRecords, LastName+", "+FirstName, JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null, "Does not exist");
}
You are calling rs.next() twice, which makes sense only if there might be at least two records.
Assuming that there can be only one student with a specific ID, the while loop does not make sense either.
The logic of your program should probably look like this:
ResultSet rs = ps.executeQuery();
if (rs.next()) {
// found
} else {
// not found
}
I am a beginner in writing programs, I have created a search record function for my assignment.
public void searchRecord(){
for(int ct = 0; ct< 1; ct++){
System.out.println("Please insert student ID");
System.out.print("Student ID: ");//prompt for student ID to search
String data = k.nextLine().trim();
String sql = "SELECT * FROM Students WHERE StudentID = '"+data+"'";
try{
rs = st.executeQuery(sql);
if(rs.next()){
displayRecord();
rs.next();
showMenu();
}
else{
System.out.print("No record found. ");
ct--;
}
}catch (Exception ex){
System.out.println("Problem searching.");
}
}
However, after I try to get data from the result, it shows Invalid Cursor State.
If I want to retrieve data, I'll have to execute the Display next record method which is:
try{
if(rs.next()){
displayRecord();
}
else{
rs.previous();
System.out.println("No more records!");
}
}catch (Exception ex){
System.out.println("There is problem showing next data.");
}
I tried adding "rs.next" at the search record method after "displayRecord" but it wouldn't solve the problem. Is there anyway to solve this?
By the way my display record method:
public void displayRecord(){//get and display data from current row of record
try{
String ID = rs.getString(1);
String fname = rs.getString(2);
String lname = rs.getString(3);
String conNo = rs.getString(4);
String mail = rs.getString(5);
String plate = rs.getString(6);
Date date = rs.getDate(7);
System.out.print("Student ID: "+ID+"\nName: "+fname+" "+lname+"\nCar Number: "+plate+"\nContact Number: 0"+conNo+"\nE-Mail Address: "+mail+"\nDate Registered: "+date);
}catch (Exception ex){
System.out.println(ex);
}
}
Any helps or advices are appreciated.
I don't quite understand what your code is supposed to do. But I suspect you don't fully understand how JDBC statements and result sets work.
If you execute a query that returns many rows, you would write something like this:
ResultSet rs = stmt.executeQuery(sqlQuery);
while (rs.next()) {
String id = rs.getString(1);
String name = rs.getString(2);
// do something with the current row
}
Note that ResultSet instance allows you to access the data from the current result row. next() both advances to the next result row and tells you if there is next row (or whether you have advanced beyond the last row). Initially, it's positioned before the first result row. So next() needs to be called before accessing the first row's data. But that's all done in the single line while (rs.next()).
In your case, I would expect that the query only returns a single result row as the StudendID is most likely a unique key. So the code would look like this:
ResultSet rs = stmt.executeQuery(sqlQuery);
if (rs.next()) {
String id = rs.getString(1);
String name = rs.getString(2);
// do something with the current row
} else {
// no student with specified ID found
}
However, you code contains two calls to next() and another one to previous(), which is confusing.
There error message Invalid Cursor State indicates that you are trying to access the current row's data when in fact the result set is position before the start or after the end of the result set.