Connection from Java Application and Stored Procedure MSSQL - java

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();
}
}

Related

Delete from SQLite Database

I have an SQLite database linked up to my Java project within Eclipse. I'm able to delete entries from the database when I give a hardcoded, specified ID such as '3'. I'm trying to alter the code in order to enable the user the manually pass any number and have it delete that entry.
public static String deleteRecords(String NumberDelete){
Connection dbConnection = null;
Statement statement = null;
try{
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
statement = dbConnection.createStatement();
String sql = "DELETE from employees where ID='NumberDelete';";
statement.executeUpdate(sql);
dbConnection.commit();
statement.close();
dbConnection.close();
} catch(Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return NumberDelete;
}
You need to use PreparedStatement to pass the parameters to query and execute it, the method will look like this:
public static String deleteRecords(String NumberDelete) {
Connection dbConnection = null;
PreparedStatement statement = null;
String sql = "DELETE from employees where ID= ? ;";
try {
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
statement = dbConnection.prepareStatement(sql);
statement.setString(1, NumberDelete);
statement.executeUpdate(sql);
dbConnection.commit();
statement.close();
dbConnection.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return NumberDelete;
}
This will set the number in the query and execute it. If the number is of type int then you need to use setInt to set the value. Here is the javadoc for PreparedStatement.
For user input, you might want to check out the Scanner class: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Once you get an integer from the user, parse it, and store it in a variable, you can simply use String concatenation:
String sql = "DELETE from employees where ID='" + userInput + "';";

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

jlabels isn't showing the results in the jlabels

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));
}
}

Pull string from sql to java

I am trying to pull a first name and last name from a table in my SQL database. The queries work fine in SQL without the "as First" part and I know the db connection is fine since it works in every other part of the code.
The error I receive is that table "First" does not exist, but it should be looking at firstName and lastName for the table names, not First and Last.
Its inside of a for loop with "i", but those values are correct, playerid = i exists.
try {
String query2 = " SELECT firstName as First from player "
+ "WHERE playerid = ?";
PreparedStatement st2 = db.conn.prepareStatement(query);
st2.setInt(1, i);
ResultSet rs2 = st2.executeQuery();
if (rs2.next()) {
setFirstName(rs2.getString("First"));
}
String query3 = " SELECT lastName as Last from player "
+ "WHERE playerid = ?";
PreparedStatement st3 = db.conn.prepareStatement(query);
st3.setInt(1, i);
ResultSet rs3 = st3.executeQuery();
if (rs3.next()) {
setLastName(rs3.getString("Last"));
}
}
catch (SQLException e) {
e.printStackTrace();
}
Change your code into something like this:
PreparedStatement ps = null;
try {
ps = db.conn.prepareStatement("SELECT firstName, lastName from player "
+ "WHERE playerid = ?");
for (int i = 0; i < MAX_PLAYERS /*<- or what is the loop condition?*/; i++) {
ps.setInt(1, i);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
// should these methods really be called within a loop?
setFirstName(rs.getString("firstName"));
setLastName(rs.getString("lastName"));
}
rs.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (ps != null) {
ps.close();
}
}
Some considerations:
When you're using a PreparedStatement within a loop, you should create the statement once, outside of the loop and then only re-assign the bind variable(s) during each iteration.
You should minimize the number of queries you run against the DB; in your case you should select both the first and last name column in a single query.
It is important to close the resources you open up (the PreparedStatement in this case). My example shows how this is usually done (in the finally block) pre Java 7. Use the try-with-resources statement if you're using a newer Java version.

java.lang.NullPointerException - ResultSet

I am getting the following error:
java.lang.NullPointerException
at oracle.jdbc.driver.ScrollableResultSet.cacheRowAt(ScrollableResultSet.java:2086)
at oracle.jdbc.driver.ScrollableResultSet.isValidRow(ScrollableResultSet.java:2060)
at oracle.jdbc.driver.ScrollableResultSet.next(ScrollableResultSet.java:347)
at website.web.InboxReader.getkeywordImportance(InboxReader.java:832)
at website.web.InboxReader.main(InboxReader.java:54)
There are 53 rows in Mail table and 1 row in keyword table. On debugging, as soon as the line is executed kstmt.executeUpdate("UPDATE KEYWORD SET IMPORTANCE = IMPORTANCE + 1.0 WHERE SKEYWORD = '" + s2 + "'"); it goes again to keyword set.next() and throws the exception.
Here is the code:
Connection connection = connectToDatabase();
Statement mstmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String s1,s2;
ResultSet mailset = mstmt.executeQuery("SELECT * from MAIL");
System.out.println("hello in getImportance beg");
//mailset.beforeFirst();
while(mailset.next())
{
System.out.println("hello in first while");
Statement kstmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet keywordset = kstmt.executeQuery("SELECT * FROM KEYWORD");
while(keywordset.next())
{
s1=mailset.getString("SUBJECT");
System.out.println("Subject: "+s1);
s2=keywordset.getString("SKEYWORD");
System.out.println("Keyword: "+s2);
if(s1.contains(s2))
{
System.out.println("hello in if");
kstmt.executeUpdate("UPDATE KEYWORD SET IMPORTANCE = IMPORTANCE + 1.0 WHERE SKEYWORD = '" + s2 + "'");
}
}
keywordset.close();
}
mailset.close();
connection.close();
Thanks!
if you take a look at this line which seems to be problematic:
kstmt.executeUpdate("UPDATE KEYWORD SET IMPORTANCE ='" + (keywordset.getFloat("IMPORTANCE") + 1.0) + "'");
You should double check the call
keywordset.getFloat("IMPORTANCE")
This mostlikely due to the fact the the column Importance is empty for the record or that the column might not exist. Just to debug you try with
keywordset.getFloat(0);
or which ever id of a column you know exist to see if the call works.
Have you tried removing the COMMIT statement ? Because usually unless you specify otherwise the data is automatically committed so there is no need to call a commit after your statement and if you have specified the auto_commit to false then to commit you should do con.commit() and not call it through an update statement
Please see the documentation here
http://download.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
No need to call beforeFirst as you seem to expect next to behave.
public static void viewTable(Connection con) throws SQLException {
Statement stmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
Have you tried running it without keywordset.beforeFirst() and mailset.beforeFirst() ? That is not required, and it might be creating an issue in ResultSet.
kstmt.executeUpdate("UPDATE KEYWORD SET IMPORTANCE = IMPORTANCE + 1.0 WHERE SKEYWORD = '" + s2 + "'");
When this line execute in your code your keywordset ResultSet object will change because all execute methods will cause effect on ResultSet.
All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
What you have to do is create a separate object of statement for running this query so that keywordset ResultSet won't get affected ... ...:)

Categories