public static void insertData() {
String insertFirstName;
String insertLastName;
int id;
Scanner in = new Scanner(System.in);
System.out.println("insert First Name: ");
insertFirstName = in.nextLine();
System.out.println("insert Last Name: ");
insertLastName = in.nextLine();
System.out.println("First name " + insertFirstName + " Last Name "
+ insertLastName);
try {
Statement statement = null;
Class.forName(JDBC_DRIVER);
Connection con = DriverManager.getConnection(DB_URL, "", "");
System.out.println("Connection Successfull");
statement = con.createStatement();
String sql = "Select id, FirstName, LastName FROM PhoneBook";
ResultSet rs = statement.executeQuery(sql);
rs.moveToInsertRow();
rs.next();
while (rs.next()) {
rs.updateString("FirstName", insertFirstName);
rs.updateString("LastName", insertLastName);
rs.insertRow();
}
statement.close();
rs.close();
} catch (Exception e) {
System.out
.println("********************ERROR*********************");
System.out.println(e.getMessage());
}
}
i KEEP getting
******************ERROR*******************
Invalid Cursor Type: 1003
and i dont understand why. i have RS.next() and then i go through the While(rs.next()). What am i doing wrong? Please help thank you
The javadoc of moveToInsertRow() says:
The insert row is a special row associated with an updatable result set
(emphasis mine)
The javadoc of ResultSet says:
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. The following code fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by others, and that is updatable. See ResultSet fields for other options.
You need to open a updateable ResultSet:
statement = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
See the documentation for ResultSet for further information.
Besides that, it looks like you might be moving a bit too far with the rs.next() calls after the rs.moveToInsertRow();. The example in the docs shows how you should do it:
rs.moveToInsertRow(); // moves cursor to the insert row
rs.updateString("FirstName", insertFirstName);
rs.updateString("LastName", insertLastName);
rs.insertRow();
Related
The database has the same format of date. Query is working fine in Oracle DB. In java the resultset is not empty. Cannot think of the possible reason for this problem. Please help.
try {
Class.forName(driverClass);
Connection cn=null;
cn=DriverManager.getConnection(url,username,password);
Scanner sc=new Scanner(System.in);
System.out.print("Enter Ship date in yyyy-mon-dd format: ");
String str=sc.next();
System.out.println(str);
//select PO_NUMBER from PURCHASE_ORDER where SHIPDATE=TO_DATE('2021-JAN-25','YYYY-MON-
DD');
String sql = "select PO_NUMBER from PURCHASE_ORDER where
SHIPDATE=TO_DATE('"+str+"','YYYY-MON-DD')";
System.out.println("Query exec");
Statement stmt = cn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
System.out.println("Purchase Order Shipped on "+ str+" are: ");
else
System.out.println("empty rs");
while(rs.next()) {
System.out.println(rs.getInt(1));
}
cn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
OUTPUT : Enter Ship date in yyyy-mon-dd format: 2021-JAN-25
2021-JAN-25
Query exec
Purchase Order Shipped on 2021-JAN-25 are:
The answer by Elliott Frisch is spot-on. This answer provides you with some recommended practices.
Use PreparedStatement instead of Statement in case of a parametrized query in order to prevent SQL Injection.
Use try-with-resources so that the resources get closed automatically.
Using e.printStackTrace() is bad practices because the stack-trace is of no use to the end-user. The general rule is: If your method can not handle the exception (i.e. can not do something to recover from the exceptional state), it should not catch the exception and should declare throws with the method signature. This will ensure that the calling method will get an opportunity to handle the exception in the desired manner.
As per the documentation of ResultSet#next, it Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
It means that after making a call to ResultSet#next, you have to grab the value(s) from the ResultSet before making another call to ResultSet#next, which you have missed and therefore the values fetched by the ResultSet from the DB, on the first call to ResultSet#next, is getting wasted.
Either you handle it in the way, Elliott Frisch has suggested or you can do it in an alternative way shown in the following code.
Based on these recommendations, your code should be as follows:
Scanner sc = new Scanner(System.in);
System.out.print("Enter Ship date in yyyy-mon-dd format: ");
String str = sc.next();
String query = "select PO_NUMBER from PURCHASE_ORDER where SHIPDATE = TO_DATE(?, 'YYYY-MON-DD')";
try (Connection cn = DriverManager.getConnection(url,username,password);
PreparedStatement stmt = cn.prepareStatement(query)) {
stmt.setString(1, str);
ResultSet rs = stmt.executeQuery(query);
if(rs.next()) {
System.out.println("Purchase Order Shipped on "+ str+" are: ");
System.out.println(rs.getInt(1));
while(rs.next()) {
System.out.println(rs.getInt(1));
}
} else {
System.out.println("empty rs");
}
}
Your current while loop discards the first row (which is presumably the only row). Easiest solution I can see would be to change it to a do while in the if. Something like,
if(rs.next()) {
System.out.println("Purchase Order Shipped on " + str + " are: ");
do {
System.out.println(rs.getInt(1));
} while(rs.next());
} else {
System.out.println("empty rs");
}
The user must choose a Resort ID from the table that is displayed and the make a booking. I can't seem to find my problem, I want to print the name of the Resort that they are making a booking at.
String x = jTextFieldID.getText();
Integer Resort = Integer.valueOf(x);
int resort = Integer.parseInt(x);
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = "+Resort;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, resort);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String resortName = rs.getString("RESORT_NAME");
JOptionPane.showMessageDialog(null,
"You want to book at " + resortName);
}
You have to use rs.next() :
ResultSet rs = pstmt.executeQuery(sql);
String resortName = "";
if(rs.next()){//<<-----------------------------
resortName = rs.getString("RESORT_NAME");
}
JOptionPane.showMessageDialog(null, "You want to book at "+resortName);
If you want to get many results you can use while(rs.next){...} instead.
Note? for a good practice, don't use upper letter in beginning for the name of your variables ResortName use this instead resortName
You need to test over the ResultSet result before trying to read from it:
if(rs.next()) {
String ResortName = rs.getString(1);
JOptionPane.showMessageDialog(null, "You want to book at "+ResortName);
}
And you can use getString(1) to get the RESORT_NAME, check ResultSet .getString(int index) method for further details.
The error is that sql is passed to Statement.executeQuery(String) too, instead of the PreparedStatement.executeQuery().
int resort = Integer.parseInt(x);
//String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = ?";
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = " + resort;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
//pstmt.setInt(1, resort);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String resortName = rs.getString("RESORT_NAME");
JOptionPane.showMessageDialog(null,
"You want to book at " + resortName);
}
}
} catch (SQLException ex) {
Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
}
Commented is the alternative usage of a prepared statement (as normally used).
Also you should close statement and result set, which can be done automatically with try-with-resources as above.
Oh, oversaw almost, that rs.next() must be called. (The others already mentioned.)
I'm trying to make login code in java but there's some problem in my code.
If I enter correct data or wrong one still can't enter the loop to
go to next frame.
This is full code it's already have exception so it's not the problem .
Connection conn = null ;
try
{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB?"+
"user=name&password=pass&characterEncoding=utf8");
String query = ("Select User_Name from user where User_Name = '" + txtUserName + "'
and password = '" + passwordField.getPassword().toString() + "' ; ");
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
while (rs.wasNull()) {
System.out.println("true");
frame2.setVisible(true);
frame.setVisible(false);
break;
}
}
catch (SQLException ee)
{
JOptionPane.showMessageDialog(frame2, "Wrong inf ... please try again ");
}
I try this too but still not working.
Connection conn = null ;
try
{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB?"+
"user=name&password=pass&characterEncoding=utf8");
PreparedStatement stmt = null;
String query = "Select User_Name from user where User_Name =? and password=?";
stmt = conn.prepareStatement(query);
stmt.setString(1, txtUserName.getText());
stmt.setString(2, passwordField.getPassword().toString());
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("true");
frame2.setVisible(true);
frame.setVisible(false);
break;
}
}
catch (SQLException ee)
{
JOptionPane.showMessageDialog(frame2, "Wrong inf ... please try again ");
}
I'm not really a Java programmer but a quick glance at your code and the descriptions of ResultSet::wasNull() ResultSet::next() show me you're misusing or misunderstanding how those work.
wasNull() tells you if the current column contains a null. An empty set is not null!
next() moves the cursor forward one row and returns true if the new current row is valid. False otherwise. In other words, if you have zero or one valid row, next() will immediately return false.
So, let's put things together.
Case 1: Using wasNull():
Enter valid data. ResultSet contains a non-null result. wasNull() returns false, don't enter while loop.
Enter invalid data. ResultSet contains an empty set result. wasNull() returns false, don't enter while loop.
Case 2: Using next():
Enter valid data. ResultSet contains a single non-null result. next() moves to next row [which is invalid] and returns false, don't enter while loop.
Enter invalid data. ResultSet contains a single empty set result. next() moves to next row [which is invalid] and returns false, don't enter while loop.
Might I suggest spending some time reading the ResultSet API documentation: https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
I need to assign a string taken by a query from the database to a Jlabel. I tried many methods but failed. How can i do it?
try{
String sql="SELECT MAX(allocationID) FROM allocation where unit='"+ dept + " ' ";
pst=conn.prepareStatement(sql);
String x= (pst.execute());
}
catch(Exception e){
}
Need to study the steps to connect to the database in java First db steps
Get the resultset from the statment by calling ResultSet rs = pst.execute();
Iterate through the list of rows by using the resultset object.
After that assign the value to the JLabel.
You just made several errors in your tiny program, take a look at the code below as an example:
// your way of using prepared statement is wrong.
// use like this
String sql="SELECT MAX(allocationID) FROM allocation where unit=?;";
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
// assign values to the variables in the query string
ps.setString(1, dept);
// execute the query
ResultSet rst = ps.executeQuery();
// parse the result set to get the value
// You'd better do some check here to ensure you get the right result
rst.next();
String x = rst.getInt(1) + "";
ps.close();
conn.close();
}
Have a look at the article if you are interested:https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
heres my code :
code for connecting database :
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=city_mart;user=sa;password=aptech");
Statement st=con.createStatement();
String sql="Select Emp_login_ID from employee where Emp_login_ID = '"+r3.getText()+"' ";
ResultSet rs=st.executeQuery(sql);
String login = rs.getString(1);
if (r3.getText().equalsIgnoreCase(login))
{
JOptionPane.showMessageDialog(rootPane, "Login ID not available.");
}
else
{
JOptionPane.showMessageDialog(rootPane, "Login ID is available.");
}
thanks.any help is much appreciated.
You have forgotten to call ResultSet#next() before calling ResultSet#getString()
First move the cursor at the the first row then get value of any column.
I suggest you to use PreparedStatment instead of Statement.
Read tutorial on Using Prepared Statements and When we use PreparedStatement instead of Statement?
It should be like this: (check the value returned by rs.next())
String sql="Select Emp_login_ID from employee where Emp_login_ID = ?";
PreparedStatement st = con.prepareStatement(sql);
st.setString(1,r3.getText());
ResultSet rs=st.executeQuery(sql);
if(rs.next()){
String login = rs.getString(1);
JOptionPane.showMessageDialog(rootPane, "Login ID is available.");
}else{
JOptionPane.showMessageDialog(rootPane, "Login ID not available.");
}
You can try :
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=city_mart;user=sa;password=aptech");
Statement st=con.createStatement();
String sql="Select Emp_login_ID from employee where Emp_login_ID = '"+r3.getText()+"' ";
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
String login = rs.getString(1);
if (r3.getText().equalsIgnoreCase(login))
{
JOptionPane.showMessageDialog(rootPane, "Login ID not available.");
}
else
{
JOptionPane.showMessageDialog(rootPane, "Login ID is available.");
}
}
Moves the cursor froward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
You can read about Next method of Result Set here
It will throw an exception because you have failed to call ResultSet.next(). If you had called it, it would have returned false, and you shouldn't have called rs.getString() at all.