jlabels isn't showing the results in the jlabels - java

try {
Statement stmt = conn.createStatement();
String sql = "CREATE OR REPLACE FUNCTION search_admin(p_username IN varchar2) \n"+
"RETURN SYS_REFCURSOR \n" +
"AS \n" +
"my_cursor SYS_REFCURSOR; \n" +
"BEGIN \n" +
"OPEN my_cursor FOR SELECT * FROM login where username=p_username; \n" +
"RETURN my_cursor; \n" +
"END; \n";
stmt.execute(sql);
CallableStatement cstmt = conn.prepareCall("BEGIN " + "? :=search_admin(?); " + "END; ");
cstmt.registerOutParameter(1, OracleTypes.CURSOR);
cstmt.setString(2, UserText3.getText());
cstmt.execute();
rs = (ResultSet) cstmt.getObject(1);
if(!rs.isBeforeFirst()) {
JOptionPane.showMessageDialog(null, "Invalid Username");
}
else {
DeleteTable.setModel(DbUtils.resultSetToTableModel(rs));
DeleteTable.setEnabled(false);
}
while(rs.next()) {
NameLabel.setText(rs.getString("name"));
UsernameLabel.setText(rs.getString("username"));
PasswordLabel.setText(rs.getString("password"));
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
i want show the username, name, password in the jlabels but it is not showing... i have a stored function in database named search_admin. when i execute the program no errors in shown but the jlabels don't show up the resultset data.

This line seems to exhaust the ResultSet :
DbUtils.resultSetToTableModel(rs)
Assuming that it returns an instance of TableModel, you could browse its content this way, rather than attempting to read the ResultSet again :
for(int i =0;i<model.getRowCount();i++){
for(int j=0;j<model.getColumnCount();j++){
System.out.println(model.getValueAt(i, j));
}
}

Related

The error shows The column name 2015-2016 was not found in this resultset

I'm Wondering what could be the possible error in this code. I'm trying to display a data in the text box from the search query. It seems there's been a problem in the Result set.
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
if (txtsearch.getText().isEmpty()) {
txtaccountnumber.setText(null);
txtfirstname.setText(null);
txtmiddlename.setText(null);
txtlastname.setText(null);
cbgender.setSelectedIndex(0);
txtage.setText(null);
txtdateofbirth.setText(null);
txtplaceofbirth.setText(null);
txtaddress.setText(null);
txtnameofguardian.setText(null);
txtoccupation.setText(null);
txtaddressofguardian.setText(null);
txtstudentfatherfirstname.setText(null);
txtstudentfathermiddlename.setText(null);
txtstudentfatherlastname.setText(null);
txtstudentmotherfirstname.setText(null);
txtstudentmothermiddlename.setText(null);
txtstudentmotherlastname.setText(null);
txtreligion.setText(null);
txttribe.setText(null);
txtcitizenship.setText(null);
txtelementary.setText(null);
txtintermediate.setText(null);
txtgrade7.setText(null);
cbgrade7schoolyear.setSelectedIndex(0);
txtgrade8.setText(null);
cbgrade8schoolyear.setSelectedIndex(0);
txtgrade9.setText(null);
cbgrade9schoolyear.setSelectedIndex(0);
txtgrade10.setText(null);
cbgrade10schoolyear.setSelectedIndex(0);
txtgrade11.setText(null);
cbgrade11schoolyear.setSelectedIndex(0);
txtgrade12.setText(null);
cbgrade12schoolyear.setSelectedIndex(0);
} else {
try {
conn = mycon.con;
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from student where studfirst like'" + txtsearch.getText().toUpperCase() + "'");
while (rs.next()) {
txtaccountnumber.setText(rs.getString(1));
txtfirstname.setText(rs.getString(2));
txtmiddlename.setText(rs.getString(3));
txtlastname.setText(rs.getString(4));
cbgender.setSelectedItem(rs.getString(5));
txtage.setText(rs.getString(6));
txtplaceofbirth.setText(rs.getString(7));
txtdateofbirth.setText(rs.getString(8));
txtaddress.setText(rs.getString(9));
txtnameofguardian.setText(rs.getString(10));
txtoccupation.setText(rs.getString(11));
txtaddressofguardian.setText(rs.getString(12));
txtstudentfatherfirstname.setText(rs.getString(13));
txtstudentfathermiddlename.setText(rs.getString(14));
txtstudentfatherlastname.setText(rs.getString(15));
txtstudentmotherfirstname.setText(rs.getString(16));
txtstudentmothermiddlename.setText(rs.getString(17));
txtstudentmotherlastname.setText(rs.getString(18));
txtreligion.setText(rs.getString(19));
txttribe.setText(rs.getString(20));
txtcitizenship.setText(rs.getString(21));
txtelementary.setText(rs.getString(22));
txtintermediate.setText(rs.getString(23));
txtgrade7.setText(rs.getString(24));
cbgrade7schoolyear.setSelectedItem(rs.getString(25));
txtgrade8.setText(rs.getString(26));
cbgrade8schoolyear.setSelectedItem(rs.getString(27));
txtgrade9.setText(rs.getString(28));
cbgrade9schoolyear.setSelectedItem(rs.getString(29));
txtgrade10.setText(rs.getString(30));
cbgrade10schoolyear.setSelectedItem(rs.getString(rs.getString(31)));
txtgrade11.setText(rs.getString(32));
cbgrade11schoolyear.setSelectedItem(rs.getString(33));
txtgrade12.setText(rs.getString(34));
cbgrade12schoolyear.setSelectedItem(rs.getString(35));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error" + e.getMessage());
}
}
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
conn = mycon.con;
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from student where studfirst like'" + txtfirstname.getText().toUpperCase() + "' or
studmiddle like'" + txtmiddlename.getText().toUpperCase() + "%' or
stud_last like'" + txtlastname.getText().toUpperCase() + "%' or
accountnumber like'" + txtaccountnumber.getText().toUpperCase());
while (rs.next()) {
txtaccountnumber.setText(rs.getString(1));
txtfirstname.setText(rs.getString(2));
txtmiddlename.setText(rs.getString(3));
txtlastname.setText(rs.getString(4));
cbgender.setSelectedItem(rs.getString(5));
txtage.setText(rs.getString(6));
txtplaceofbirth.setText(rs.getString(7));
txtdateofbirth.setText(rs.getString(8));
txtaddress.setText(rs.getString(9));
txtnameofguardian.setText(rs.getString(10));
txtoccupation.setText(rs.getString(11));
txtaddressofguardian.setText(rs.getString(12));
txtstudentfatherfirstname.setText(rs.getString(13));
txtstudentfathermiddlename.setText(rs.getString(14));
txtstudentfatherlastname.setText(rs.getString(15));
txtstudentmotherfirstname.setText(rs.getString(16));
txtstudentmothermiddlename.setText(rs.getString(17));
txtstudentmotherlastname.setText(rs.getString(18));
txtreligion.setText(rs.getString(19));
txttribe.setText(rs.getString(20));
txtcitizenship.setText(rs.getString(21));
txtelementary.setText(rs.getString(22));
txtintermediate.setText(rs.getString(23));
txtgrade7.setText(rs.getString(24));
cbgrade7schoolyear.setSelectedItem(rs.getString(25));
txtgrade8.setText(rs.getString(26));
cbgrade8schoolyear.setSelectedItem(rs.getString(27));
txtgrade9.setText(rs.getString(28));
cbgrade9schoolyear.setSelectedItem(rs.getString(29));
txtgrade10.setText(rs.getString(30));
cbgrade10schoolyear.setSelectedItem(rs.getString(rs.getString(31)));
txtgrade11.setText(rs.getString(32));
cbgrade11schoolyear.setSelectedItem(rs.getString(33));
txtgrade12.setText(rs.getString(34));
cbgrade12schoolyear.setSelectedItem(rs.getString(35));
}
} catch (Exception e) {}
You have to clarify the error what do you get. Apart from that what I can see is issue with sql query part.
First thing you must use PreparedStatement when you have to deal with dynamic or runtime parameters.
Change this below code:
stmt.executeQuery("select * from student where studfirst like'" + txtsearch.getText().toUpperCase() + "'");
As this:
String sql="select * from student where studfirst like '?'";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,txtsearch.getText().toUpperCase());
rs=ps.executeQuery();
Also you need to rectify the below query, BTW, you cannot break lines as you done in the below query.
"select * from student where studfirst like'" + txtfirstname.getText().toUpperCase() + "' or
studmiddle like'" + txtmiddlename.getText().toUpperCase() + "%' or
stud_last like'" + txtlastname.getText().toUpperCase() + "%' or
accountnumber like'" + txtaccountnumber.getText().toUpperCase());
Must be some what like this:
String sql="select * from student where studfirst like '?' or studmiddle like '?%' or stud_last like'?%' or accountnumber like '?'";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,txtsearch.getText().toUpperCase());
ps.setString(2,txtlastname.getText().toUpperCase());
ps.setString(3,txtaccountnumber.getText().toUpperCase());
rs=ps.executeQuery();

java derby database query, with user input text

I have a java derby database, I can write to and read from the database.
I am having trouble:
Making it so that the text that the user enters into the text field, is then incorporated into the database query to determine the results displayed.
I tried it this way, the results were, if I click the search button, it will return the info/query into the "run" screen, not actually incorporating the user input into the query tho, I have to do that in the code, by replacing the abc to the number in the database.
Do I have to create some kind of command line argument? set the variable differently? Can I just replace the query info where the database info goes with a variable like how I tried in the upcoming example?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String abc = jTextField1.getText();
String data = "jdbc:derby://localhost:1527/sample";
try (
Connection conn = DriverManager.getConnection(
data, "app", "app");
Statement st = conn.createStatement()) {
Class.forName("org.apache.derby.jdbc.ClientDriver");
ResultSet rec = st.executeQuery(
"select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 "
+ "where (ROW4 = 'abc')");
while (rec.next()) {
System.out.println("ROW1:\t"
+ rec.getString(1));
System.out.println("ROW2:\t" + rec.getString(2));
System.out.println("ROW3:\t" + rec.getString(3));
System.out.println("ROW4:\t" + rec.getString(4));
System.out.println("ROW5:\t" + rec.getString(5));
System.out.println();
}
st.close();
} catch (SQLException s) {
System.out.println("SQL Error: " + s.toString() + " "
+ s.getErrorCode() + " " + s.getSQLState());
} catch (Exception e) {
System.out.println("Error: " + e.toString()
+ e.getMessage());
}
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
You are not setting the variable correctly. Instead of setting the ROW4 to 'abc' you need to set the variable. Try this.
"select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 " + "where (ROW4 = '"+abc+"')"
Its always better to use preparedStatement. this will avoid lot of problem related to SQL Injection.
String selectSQL = "select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 where ROW4 = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, abc);
ResultSet rs = preparedStatement.executeQuery(selectSQL );

Java SQLite Select Query

I am trying to complete my Java Code to execute a SELECT Query that will write the Results into Sysout.
Here is my Code:
public void PullFromDB() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
String sql = "SELECT * FROM " + Name + ";";
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
Integer ID = rs.getInt("id");
System.out.println("ID = " + ID.toString());
String entry = rs.getString(Properties.get(j));
System.out.println(Properties.get(j) + "=" + entry);
j++;
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
When I sysout my SQL Query it looks like this:
CREATE TABLE IF NOT EXISTS Cars(ID INTEGER PRIMARY KEY AUTOINCREMENT,AnzSitze TEXT,Marke TEXT,Pferdestärke TEXT);
INSERT INTO Cars(AnzSitze,Marke,Pferdestärke) VALUES('vier','Audi','420');
SELECT * FROM Cars;
Those are just some examples I put in.
maybe create and propabley insert has failed, i see none-ascii characters in filed name Pferdestärke try to use valid names
check this
Permitted characters in unquoted identifiers:
ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar,
underscore)
Extended: U+0080 .. U+FFFF
so replace the filed name Pferdestärke to Pferdestarke in all qrys and try again

No such Table Sqlite JDBC

Yo guys. The problem I'm facing is pretty weird..
I am creating a table at first, then trying to put data on it, but for somereason something is ticking off. It says
[SQLITE_ERROR] SQL error or missing database (no such table: Name)
Aaand here's my basic code..
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
stmt = conni.createStatement();
String sql = "CREATE TABLE " + project.getText() + " (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , Name TEXT, One TEXT, Two TEXT)";
stmt.executeUpdate(sql);
stmt.close();
conni.close();
}catch (Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String query1 = "insert into Name (Name) values(?)";
PreparedStatement pst = conni.prepareStatement(query1);
pst.setString(1, project.getText());
pst.execute();
pst.close();
conni.close();
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String query1 = "insert into " + project.getText() + "(Name, One, Two) values(?,?,?)";
PreparedStatement pst = conni.prepareStatement(query1);
pst.setString(1, project.getText());
pst.setString(2, textField_one.getText());
pst.setString(3, textFieldtwo.getText());
pst.execute();
pst.close();
conni.close();
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
JOptionPane.showMessageDialog(null, "Thank you");
Thank you for the help! I really can understand... I guess the table is not being created at all, but it actually worked once. So It gets me even more confused o.o
Name is a MySql reserved keyword. Rename the table to something else.
Please encase your fieldnames with " to escape them.
String sql = "CREATE TABLE \"" + project.getText() + "\" (\"Id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , \"Name\" TEXT, \"One\" TEXT, \"Two\" TEXT)";
String query1 = "insert into \"Name\" (\"Name\") values(?)";
String query1 = "insert into \"" + project.getText() + "\" (\"Name\", \"One\", \"Two\") values(?,?,?)";
Also... I'm assuming you've patched together these code snippets from various points in your code..
But i advice you to set up a SINGULAR database connection in your code and to reuse that connection throughout your application.
Something along the lines of:
public class MyApp {
public static Connection DB;
public void initDatabase() {
try {
MyApp.DB = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
}
catch(Exception ex) {
}
}
public static void main(String args[]) {
MyApp app = new MyApp();
app.initDatabase();
}
}

Connection from Java Application and Stored Procedure MSSQL

I have the stored procedure in SQL Sever and it has a few parameter. I would like to give the value of parameter from the combo box (in java application). I've read this code (look at below)
public static void executeSprocInParams(Connection con) {
try {
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");
pstmt.setInt(1, 50);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();
pstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
But i didn't get the meaning. Is there any tutorial that give me some example just like in my case? Thanks for any reply
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");
pstmt.setInt(1, 50);
ResultSet rs = pstmt.executeQuery();
1) Line 1 creates a prepare statement object with your Stored Procedure. The ? is the placeholder for the input parameter to the Stored Procs
2) Line 2 sets the input param to the stored proc
3) executeQuery executes the stored proc by providing the input and get the output as a resultset.
while (rs.next()) {
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();
pstmt.close();
Above lines iterate over the result set and print each record
public static void executeSprocInParams(Connection con) {
try {
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");//Creating a prepared statement with the string to execute your procedure.
pstmt.setInt(1, 50);//This is to set the parameter to the place holder '?'
ResultSet rs = pstmt.executeQuery();//This is to execute your procedure and put the result into a table like set
while (rs.next()) {//To check if there are any values in the set, if so the print those values
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();//close the set
pstmt.close();//close the statement
}
catch (Exception e) {
e.printStackTrace();
}
}

Categories