I have a question. In my method
public void selectUser(String name, String surname)
I try to log user. How I can prepare an sql statment like this one:
String sql = "select * from user where surname= (here my surname from method parameter) and name= (name from method parameter) ";
Inialize your PreparedStatement object
PreparedStatement pst = null;
pst = c.prepareStatement("select * from user where surname= ? and name= ? ");
pst.setString(1, getterMethodHere);
pst.setString(2, getterMethodHere);
1,2 represents the surname= ? and name= ? symbol respectively
Learn More . .
San Krish thanks. Now how to use rs.next because i don;t understand prepareStatemnt.
Here's the code
enter code here
//stat = con.createStatement();
//String sql = "select * from user where surname= "+surname+" and name="+name;
PreparedStatement pst = null;
pst = con.prepareStatement("select * from user where surname= ? and name= ? ");
pst.setString(1, name);
pst.setString(2, surname);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
//get from column name
String id = rs.getString("id");
String login = rs.getString("login");
String password = rs.getString("password");
//print
System.out.print(" id: " + id);
System.out.print(", login: " + login);
System.out.println(", pass: " + password);
}
and how to return id ?
Related
This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 4 years ago.
Sql query how to pass the id from department table using the department name to the user table using the department id
here in department table dept_id is primary key
and dept_id in user table is foreign key
how to select the dept_id using department_name from the department table and store the value in the user table
try{
Connection con = DBconnect.getConnection();
//selecting the dpartment
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
String s11=comboboxdeptid.getItems().toString();
ResultSet rs=ps.executeQuery();
if(rs.next()==true)
{
if(rs.getString("DEPARTMENT_NAME").equals(comboboxdeptid.getSelectionModel().toString()))
rs.getString("DEPARTMENT_CODE");
}
//second stmt
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
String s12 = nameid.getText();
String s13 = Firstnameid.getText();
String s14 = Lnameid.getText();
String s15 = desigid.getText();
String s16 = comboboxdeptid.getItems().toString();
String s17 = addrsid.getText();
String s18 = passwordid.getText();
ps.setString(1, s12);
ps.setString(2, s13);
ps.setString(3, s14);
ps.setString(4, s15);
ps.setString(5, s17);
ps.setString(6, s18);
ps.setString(7, s11);
ps.setString(8, "abc");
ps.execute();
ResultSet rs1=ps1.executeQuery();
//third stmt
String sql2 = "update security_qa_info set SECURITY_QUESTION=?, SECURITY_ANSWER=? where USER_ID=?";
PreparedStatement ps2 = con.prepareStatement(sql2);
String s19 = securityquestionid.getSelectionModel().getSelectedItem().toString();
String s20 = answerid.getText();
while(rs2.next()==true)
{
if(rs2.getString("USER_NAME").equals(nameid.getText()))
{
rs2.getString("USER_ID");
ps2.setString(1, s16);
}
}
ps2.setString(2, s19);
ps2.setString(3, s20);
ps2.executeUpdate();
showMessageDialog(null, "Registration Successful");
}catch(Exception e){
// showMessageDialog(null, e);
e.printStackTrace();
}
Parent fxml = FXMLLoader.load(getClass().getResource("/com/abc/fxml/LoginPage.fxml"));
pane2.getChildren().setAll(fxml);
} else {
showMessageDialog(null, "Passwords don't match!");
}
}
ps = prepared statement for SELECT query:
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
ps1 = prepared statement for INSERT statement:
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
Using the wrong prepared statement:
ps.setString(1, s12);
A suggestion - if you call the first prepared statement 'selectDepartmentDetails' and the second 'insertUserInfo', it is less likely you will run into this.
i have a problem >>
programming language: java
Data base: Mysql database
i write a java code for retrive the record from the database based on the data parameters comping from the method>>
the code is:
public static void Get_patient_data(String Hospital1_ID,String Hospital2_ID {
try {
Connection con = getConnection2();
PreparedStatement statement = (com.mysql.jdbc.PreparedStatement)
con.prepareStatement(
"SELECT PatientGender "+
"FROM patientcorepopulatedtable "+
"WHERE PatientID = Hospital1_ID LIMIT 1" );
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while( result.next()) {
System.out.print("the patient Gender is" +
result.getString("PatientGender"));
}
}
catch(Exception e) {
System.out.println("Error"+e);
}
}
As you see the problem is Hospital1_ID parameter .. is coming from the method and the patientID is a column in a table patientcorepopulatedtable ...
the = equal operator doesn't work.
Try this
String query =
"SELECT PatientGender FROM patientcorepopulatedtable "+
" WHERE PatientID = ? LIMIT ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, Hospital1_ID);
preparedStmt.setInt (2, 1);
preparedStmt.executeQuery();
you can do it this way
PreparedStatement statement = (com.mysql.jdbc.PreparedStatement)
con.prepareStatement(
"SELECT PatientGender FROM patientcorepopulatedtable "+
"WHERE PatientID = ? LIMIT 1");
statement.setString(1, Hospital1_ID);
ResultSet result = statement.executeQuery();
you can find more info here
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String query;
boolean login = false;
String username = jTextField1.getText();
String password = jTextField2.getText();
try{
query = "SELECT (cUsername AND cPassword) FROM Customer WHERE cUsername = '"+username+"' AND cPassword = '"+password+"'";
pst = conn.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.executeQuery();
String userCheck = rs.getString(1);
String passCheck = rs.getString(2);
if((userCheck.equals(username)) && (passCheck.equals(password)))
{
login = true;
System.out.println("It actually works?!");
}
else
{
login = false;
System.out.println("Psyche, that's the wrong number!");
}
}
catch(Exception e){
System.out.println(e);
}
System.exit(0);
}
I'm currently having difficulty implementing a login system in my code. I'm trying to retrieve the text from username and password jTextFields and then query them to the database but it's not working. At the moment I'm getting
java.lang.ArrayIndexOutOfBoundsException: 0
and I unfortunately have no idea why. Any help would be GREATLY appreciated.
Your query and the logic behind got a lot of work to do:
First of all, if you want a parametrised query, you must use '?' instead of the value. Then the pst.setString will work.
Secondly, you must affect the pst.executeQuery(); to a ResultSet
query = "SELECT cUsername, cPassword FROM Customer WHERE cUsername = ? AND cPassword = ?";
pst = conn.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
String userCheck = rs.getString(1);
String passCheck = rs.getString(2);
}
I have 5 or table table to query from \
my syntax i like this
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
When i output the sql using system.out.println(sql2);
values are not set in sql2
When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery();
String sqlStatment = "SELECT * FROM " + tableName + " WHERE Patient_ID = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sqlStatment);
preparedStatement.setint(1, patientId);
ResultSet resultSet = preparedStatement.executeQuery();
public void getByIdEmployer() throws SQLException {
Connection con = null;
try {
con = jdbcUtil.connectionDtls();
PreparedStatement ptst = con.prepareStatement(getById);
ptst.setInt(1, 4);
ResultSet res = ptst.executeQuery();
while (res.next()) {
int empid = res.getInt(1);
System.out.println(empid);
String name = res.getString(2);
System.out.println(name);
int salary = res.getInt(3);
System.out.println(salary);
String location = res.getString(4);
System.out.println(location);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
}
}
I am building a simple security system using java (eclipse) and I am using the MYSQL statement to pull data from the database
ResultSet rs = statement.executeQuery("select name, username, password from securitysystem.employee where username = '" + username + "' and password = '" + password + "'");
but what if i wanted to create a variable user= name, how would I do that? name is referring to the name retrieved using the statement above.
Firstly, you should never put your parameter right into a query string.
Instead, do this:
PreparedStatement ps = connection.prepareStatement("select name, username, password "+
"from securitysystem.employee where username = ? and password = ?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
To get the results, do this:
if (rs.next()) { //move to 1st result row
String name = rs.getString(1); //first result column
String user = rs.getString(2); //second result column
// ..etc
}
How about:
while(rs.next()) {
String user = rs.getString("name");
}