How to get the primary key to execute an select statement [duplicate] - java

This question already has answers here:
How to get the primary key to execute an update statement [closed]
(2 answers)
Closed 6 years ago.
I'm trying to update my table using Java JDBC. But I don't have any idea how can I call my primary key using prepared statement. I try to make an USER_ID object for the column of my database but don't know how where to start. How will I determine if I already updated my Database?
INSERT
private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
String inputEmployee = employeeTf.getText();
String inputDepartment = departmentTf.getText();
if(inputEmployee.isEmpty() && inputDepartment.isEmpty()){
JOptionPane.showMessageDialog(null, "Please fill up!");
}
else if(inputEmployee.isEmpty()){
JOptionPane.showMessageDialog(null, "Please enter your username");
}
else if(inputDepartment.isEmpty()){
JOptionPane.showMessageDialog(null, "Please enter your password");
}
else{
String myQuery = "INSERT INTO SAMPLE (EMPLOYEENAME,DEPARTMENT) VALUES (?,?)";
try(Connection con = DBUtilities.getConnection(DBType.JDBC);
PreparedStatement myPs = con.prepareStatement(myQuery);
){
myPs.setString(1, employeeTf.getText());
myPs.setString(2, departmentTf.getText());
myPs.executeUpdate();
System.out.print("Record is inserted");
} catch (SQLException ex) {
DBUtilities.processException(ex);
}
}
}
Here if I insert a new value it will load the new values to database.
SELECT
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {
String searchEmployee = searchName.getText(); //SWING COMPONENTS
String searchDept = searchDepartment.getText();//SWING COMPONENTS
String selectQuery = "SELECT EMPLOYEENAME,DEPARTMENT FROM SAMPLE WHERE USER_ID = ?";
try {
Connection con = DBUtilities.getConnection(DBType.JDBC);
PreparedStatement myPs = con.prepareStatement(selectQuery,ResultSet.CONCUR_UPDATABLE,ResultSet.TYPE_SCROLL_INSENSITIVE);
ResultSet myRs = myPs.executeQuery();
while(myRs.next()){
String name = myRs.getString(1);
String department = myRs.getString(2);
}
} catch (SQLException ex) {
DBUtilities.processException(ex);
}
}
SCREENSHOT
After filling out the fields for searchName and searchDepartment textfields. As you can see here I here hit the "Search" button.
I want the value of searchName and searchDepartment will print out to the textfield of employeeTf and departmentTf
How will I use the setText here?

while(myRs.next()){
String name = myRs.getString(1);
String department = myRs.getString(2);
nameText.setText(name);
deptText.setText(department);
}
i supposed nameText and deptText are the object of swing text component
if these are not accessible here..then you can create object of all field and put data from result set and return the object and use there.

Related

JAVA GUI - GET and SHOW DATA FROM MYSQL

I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.
public void findVendor() {
String vatEntered = vendorID.getText();
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
ResultSet resultSet = st.executeQuery(check);
boolean status = true;
if(resultSet.next()==status){
nameSelected.setText(resultSet.getString(1));
adressSelected.setText(resultSet.getString(2));
countrySelected.setText(resultSet.getString(3));
vatSelected.setText(resultSet.getString(4));
ptermsSelected.setText(resultSet.getString(5));
conn.close();
}
else {
JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new CreateVendor().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:
String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
But it is better to use a prepared statement instead.
String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:
String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
where resultSet.getString(1); would be data from column1.

Get next record from SQLite database when button is clicked

I have read notes about this but none seems to work for me. I have an SQLite database and with Netbeans as my IDE, I have a jframe that displays data records in a jtable, with records displayed in ascending order. Clicking on a record displays them in jtextfields.
I want to move to next record in database in ascending order when I click on a button, but it doesn't seem to work. What am I doing wrong?
try{
String sql ="select * from Employees order by Name ASC";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
int i = rs.getInt("ID");
String idi= Integer.toString(i);
id.setText(idi);
String a = rs.getString("Name");
name.setText(a);
String b = rs.getString("Contact");
contact.setText(b);
String c = rs.getString("Email");
email.setText(c);
String d = rs.getString("Residence");
residence.setText(d);
String e = rs.getString("Job_Type");
comboJob.setSelectedItem(e);
}
else {
rs.previous();
}
}
catch(SQLException | HeadlessException ex)
{
JOptionPane.showMessageDialog(null, ex);
}finally{
try{
rs.close();
pst.close();
}
catch(Exception e){
}
}
you need to store the values from database in an array and then iterate over it with your (prev,next) button like
i=0;
while(rs.next()) {
dataset["ID"][i]=Integer.toString(rs.getInt("ID"));
dataset["Name"][i]=rs.getString("EName");
i++
}
to display information you can use dataset array like
id.setText(dataset["ID"][i]);
name.setText(dataset["EName"][i]);
not checked syntax but the logic is correct.

cardinality violation and NullPointerException while populating a combobox with available courses

I am relativity new to java programming any way here what i am trying to do
I am trying to populate combobox1(Add list) with the courses available to the student and then removing the selected item and sending to combobox2(drop list)
but its simply not reacting right especially when the student doesn't have any courses that are available to add and it returns the exceptions
"net.ucanaccess.jdbc.ucanaccessSQLException:cardinality violation"
&
"java.lang.NullPointerException"
here's how initialize each of the comboboxes
try
{String mail=Login.user_mail;
String sql = "select CourseCode from Course where CourseCode!=(select CourseCode from CourseStudent where StudentEmail='"+mail+"') OR NOT EXISTS(select CourseCode from CourseStudent where StudentEmail='"+mail+"')";
java.sql.ResultSet rs = dbm.select(sql);
DefaultComboBoxModel m = new DefaultComboBoxModel();
while (rs.next()) {
m.addElement(rs.getObject(1).toString());
}
jComboBox1.setModel(m);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.toString());
}
then combo box2
String mail=Login.user_mail;
String sql = "select CourseCode from CourseStudent where StudentEmail='"+mail+"'";
java.sql.ResultSet rs = dbm.select(sql);
DefaultComboBoxModel m = new DefaultComboBoxModel();
while (rs.next()) {
m.addElement(rs.getObject(1).toString());
}
jComboBox2.setModel(m);
}
this is within the Add button
String ID = (String) jComboBox1.getSelectedItem();
String mail=Login.user_mail;
try {
dbm.insert(" insert into CourseStudent (StudentEmail, CourseCode ) values ('"+mail+"', '"+ID+"') ");
jComboBox2.addItem(jComboBox1.getSelectedItem());
jComboBox1.removeItem(jComboBox1.getSelectedItem());
} catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Insertion Faild\n"+ex);
}
and this is with the drop button
try {
String ID = (String) jComboBox2.getSelectedItem();
String mail=Login.user_mail;
dbm.delete("delete from CourseStudent where CourseCode='"+ID+"' And StudentEmail='"+mail+"'");
jComboBox1.addItem(jComboBox2.getSelectedItem());
jComboBox2.removeItem(jComboBox2.getSelectedItem());
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Delete Faild\n"+e);
}
i think the problem lays in the combobox1 SQl statement but i really can't see any other way to do it as i need to retrieve the courses from a table while making sure that the user doesn't take it already from another table...
any help would be greatly appreciated as i said i have been using java for a couple of weeks now and i haven't used sql before so i am a little lost

Java Database adding to row I deleted?

Ok So I have a program where I add new Players to a database, and where I load them users into a list. The problem is when I delete a user, then go to add a new user the new player gets added in to where the old user was. Basically because that spot is free now and I use:
rs.moveToInsertRow();
is there a way that when adding a new player it 'Always' adds to the end of the the database. Like when you delete a row from table to make the database compress so it has no gaps?
here is the code:
public static void Save() { try {
String Name = "#####";
String Pass= "#####";
String Host = "######";
Connection con = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "####", "####"),
Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM Accounts";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
String userName= TestForm.UsernameTextField.getText(); //make this equal to whats in textfield
String password= TestForm.PasswordTextField.getText(); //make this equal to whats in textfield
String insertQuery="insert into Accounts (`Username`,`Password`) values ('"+userName+"','"+password+"');";
stmt.executeUpdate(insertQuery);
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
What's your table create statement? SHOW CREATE TABLE Accounts ;
Seems like an AUTO_INCREMENT integer primary key in the table would help your issue.

Adding values entered in java program(in a form) to sql database:

I am trying to capture & store user details(name, password etc) & store them in sql database so as to be used by users to login in future.
How do I save the details as a row in the database, yet they are entered as individual strings?
Also, how do I capture &store details like gender(Male,Female) selected from a Combobox? Thanks.
private class achandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
//capture user details
String fnamevalue = fnametext.getText();
String lnamevalue = lnametext.getText();
String usernamevalue = usernametext.getText();
char[] pwdvalue = pwdtext.getPassword();
char[] pwdrptvalue = pwdrpttext.getPassword();
if(pwdvalue == pwdrptvalue) {
//add user details to an array
String[] userdetail = {fnamevalue, lnamevalue, usernamevalue, pwdvalue.toString()};
try {
Class.forName("com.mysql.jdbc.Driver");
String Url = "jdbc:mysql://localhost/nsibirwa?" +
"user=root&password=1234";
Connection con = DriverManager.getConnection(Url);
Statement stmt = con.createStatement();
//I am stuck here!!!! i.e. adding 'userdetail' as a tuple in the database
}
catch (SQLException e) {
System.out.println("SQL Exception: "+ e.toString());
}
catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
}
else {
JOptionPane.showMessageDialog(null, "password not matching!",
"Password error", JOptionPane.ERROR_MESSAGE);
}
}
}
adding 'userdetail' as a tuple in the database
Something like:
Connection con = DriverManager.getConnection(Url);
PreparedStatement stmt = con.prepareStatement("insert into user_details (fname, lname, username, pwd) values (?,?,?,?));
stmt.setString(1, fnamevalue);
stmt.setString(2, lnamevalue);
stmt.setString(3, username);
stmt.setString(4, new String (pwdvalue));
stmt.executeUpdate();
Your code has another problem:
if (pwdvalue == pwdrptvalue)
you can not compare objects like that. You need to convert those char[] to Strings and use equals() to compare them. Search for "java string equals" to find out why. This is very basic Java knowledge (and is covered in each and every tutorial I have seen)
This assumes you have a table named user_details with the columns fname, lname, username and pwd. If your table definition is different you need to adjust the insert statement.
Also, how do I capture &store details like gender(Male,Female) selected from a Combobox?
I would suggest you open a second question for that. You should not mix completely different topics (JDBC/SQL vs. plain Swing) in a single question.

Categories

Resources