This question already has an answer here:
ResultSet is not updatable [duplicate]
(1 answer)
Closed 4 years ago.
I am doing a simple GUI application in Java (NetBeans 7.3.1) in which I use ResultSet for retreiving and updating data in the virtual database of NetBeans.
I created the database "Employees" and a table, "WORKERS", in it. Tough, I can't update data in it.
The code is
public void doConnect() {
String host = "jdbc:derby://localhost:1527/Employees";
String uName = "adm";
String uPass = "admin";
String SQL = "SELECT * FROM APP.WORKERS ORDER BY ID";
try {
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery(SQL);
int conc = rs.getConcurrency();
System.out.println(conc);
rs.next();
int id_col = rs.getInt("ID");
String first_name = rs.getString("First_Name");
String last_name = rs.getString("Last_Name");
String job = rs.getString("Job_Title");
System.out.println(id_col + " " + first_name + " " + last_name + " " + job);
textId.setText(Integer.toString(id_col));
textName.setText(first_name);
textLast.setText(last_name);
txtJob.setText(job);
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
The outcome of getConcurrency(); is 1007 (ReadOnly).
What did I wrong? I can't find the error.
Isn't it because you make the result set updatable after rs.deleteRow(); ?
maybe if you place
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
before the rs.deleteRow(); it works.
You can try to write inside your try catch clause under your variable con this line:
con.setReadOnly(false);
If this does not solve the problem, you must find a way to access the database options within NetBeans and make sure the access and use of database objects is set to editable/updateable/read and write. I cannot help more since I use Eclipse and my NetBeans skills are a bit rusty.
Related
I have a small problem. I wrote a method in which I have an SQL query that should output a correct string after 2 parameters. When debugging, however, the result is not the right element. I don't know why this happens.
public static String findRightTemplate(String user_name, int template_id)
throws Exception {
Connection conn = DriverManager.getConnection(
"xxx", "xxx", "xxx");
Statement st = conn.createStatement();
st = conn.createStatement();
ResultSet rs = st.executeQuery(
"SELECT template FROM templates " +
"where template_id=template_id AND user_name=user_name"
);
String temp="";
while(rs.next())
{
temp=rs.getString("template");
}
rs.close();
st.close();
conn.close();
I ask for the username and template_id and I just want to get an element out of the template column.
The SQL query is correct. I've already tested that. But it seems that the query runs through all elements with the same username. As a result, I only get the last element and not the right one.
UPDATE
Currently you do not use the method parameters inside your query. As already suggested you should use a PreparedStatement to fix that. You should basically do the following:
public static String findRightTemplate(String userName, int templateId) throws SQLException {
try (final Connection connection = DriverManager.getConnection("...")) {
final PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT template " +
"FROM templates " +
"WHERE user_name = ? " +
"AND template_id = ? " +
"LIMIT 1"
);
preparedStatement.setString(1, userName);
preparedStatement.setInt(2, templateId);
final ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getString(1);
}
}
return null;
}
If you do not use a PreparedStatement and build the query manually as suggested in the comments your application could be vulnerable to SQL injection attacks.
This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 6 years ago.
this is my current java program. I need to make a prepared statement and connect to a MySql database.
try {
Connection connect = DriverManager.getConnection(host, username, password);
System.out.println("works fine connected");
/*
*
* */
String Dquery = ("SELECT * FROM ?");
//create the java statement
PreparedStatement st = connect.prepareStatement(Dquery);
st.setString(1, "lmgs_Book");
System.out.println("mySql statemnt: "+Dquery);
//execute the query, and get a java resultset
ResultSet rs = st.executeQuery();
//iterate through the java resultset
while (rs.next())
{
String id = rs.getString(Column1);
String firstName = rs.getString(Column2);/*
String lastName = rs.getString(Column3);
String dateCreated = rs.getString(Column4);
int isAdmin = rs.getInt (Column5);*/
//print the results
System.out.println(id+"|\t"+firstName/*+"|\t\t"+lastName+"|\t\t"+dateCreated+"|\t"+isAdmin*/);
}
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I cant insert the "lmgs_Book" String into the prepared statement.
Prepared statement is for the column values not for table name.
But you can use placeholder in place of table name and then replacing
that with your tablename.
String Dquery = ("SELECT * FROM $tableName");
Dquery = Dquery.replace("$tableName","lmgs_Book");
PreparedStatement st = connect.prepareStatement(Dquery);
Remove this:
st.setString(1, "lmgs_Book");
Caution:
And what is the advantage compared to
String Dquery = "SELECT * FROM lmgs_Book";? [Recommended]
Answer: No advantage at all. You may embrace potential harms if you use placeholder in table name like above.
(especially since you should not use a variable in the replace call
instead of the literal, since that might make the statement vulnerable
to SQL injection)
try this and Please make sure your queryString column Name must be a varchar in your database.
String Dquery = ("SELECT * FROM tablename where column_name =?");
//create the java statement
PreparedStatement st = connect.prepareStatement(Dquery);
st.setString(1, "lmgs_Book"); //this line will be set Imgs Books as search Parameter.
I have been searching and trying different stuff for awhile, but have not found an answer. I'm trying to make a connection to sql using JDBC from eclipse. I am having trouble when I need to select a string in the database. If I use:
Select name from data where title = 'mr';
That works with terminal/command line but when I try to use eclipse where I use
statement sp = connection.createstatement();
resultset rs = sp.executequery("select name from data where title = '" + "mr" + "'");
It does not give me anything while the terminal input does. What did I do wrong in the eclipse? Thanks
Heres a part of the code. Sorry, its a bit messy, been trying different things.
private boolean loginChecker(String cid, String password) throws SQLException{
boolean check = false;
PreparedStatement pstatment = null;
Statement stmt = null;
//String query = "SELECT 'cat' FROM customer";
String query = "select '"+cid+"' from customer where password = '"+password+"'";
try {
System.out.println("in try......");
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(query);
PreparedStatement prepStmt = con.prepareStatement(query);
ResultSet rs = prepStmt.executeQuery();
//System.out.print(rs.getString("cid"));
while(rs.next()){
check = true;
System.out.print(rs.getString("cid"));
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) {
//stmt.close();
}
}
return check;
}
Second try on a simpler query:
public List<Object> showTable() {
List<Object> result = new ArrayList<Object>();
String name = "bob";
try
{
PreparedStatement preStatement = con.prepareStatement("select total from test where name = ?");
preStatement.setString(1, name);
ResultSet rs1 = preStatement.executeQuery();
while(rs1.next()){
System.out.println("there");
System.out.println(rs1.getInt("total"));
}
}
catch (SQLException ex)
{
System.out.print("Message: " + ex.getMessage());
}
return result;
}
Remove the quotes around the column name.
String query = "select "+cid+" from customer where password = '"+password+"'";
You've not mentioned which database you're working with but many databases like Oracle change the column case to upper case unless they're quoted. So, you only quote table columns if that's how you had created them. For example, if you had created a table like
CREATE TABLE some_table ( 'DoNotChangeToUpperCase' VARCHAR2 );
Then you would have to select the column with quotes as well
SELECT 'DoNotChangeToUpperCase' FROM some_table
But, if you didn't create the table using quotes you shouldn't be using them with your SELECTs either.
Make sure you are not closing the ResultSet before you are trying to use it. This can happen when you return a ResultSet and try to use it elsewhere. If you want to return the data like this, use CachedRowSet:
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(ResultSet);
CachedRowSet is "special in that it can operate without being connected to its data source, that is, it is a disconnected RowSet object"
Edit: Saw you posted code so I thought I add some thoughts. If that is your ACTUAL code than the reason you are not getting anything is because the query is probably not returning anything.
String query = "select '"+cid+"' from customer where password = '"+password+"'";
This is wrong, for two reasons. 1) If you are using prepared statements you should replace all input with '?' so it should look like the following:
String query = "select name from customer where password = ?";
Then:
PreparedStatement prepStmt = con.prepareStatement(query);
prepStmt.setString(1, password);
ResultSet rs = prepStmt.executeQuery();
2)
System.out.print(rs.getString("cid"));
Here are are trying to get the column named "cid", when it should be the name stored in cid. You should actually never be letting the user decide what columns to get, this should be hardcoded in.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Update a record if ID exist else Insert values
I am trying to update a value if the record exists else insert the values in the database. However, that is not working. I have written the code below :
NOTE: (Moderators, this is a repeated questions that I asked few mins ago. I am not able to edit previous one. Apologies if any inconvenience. Requesting you to delete.)
<%
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:sqlserver://10.222.10.19:1433", "sa", "admin1");
String empId = request.getParameter("empid");
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String sqlCheck = "Select * from [UAP].[dbo].[UAP_EMPLOYEE] where EMP_EMPLOYEE_ID = "empId" ";
PreparedStatement prpStatementCheck = conn.prepareStatement(sqlCheck);
prpStatementCheck.setInt(1, Integer.parseInt(empId));
prpStatementCheck.setString(2, fName);
prpStatementCheck.setString(3, lName);
ResultSet rsCheck=prpStatementCheck.executeQuery();
String check=null;
boolean exists = false;
while(rsCheck.next())
{
Statement stmt = conn.createStatement();
String sql= "UPDATE [UAP].[dbo].[UAP_EMPLOYEE] SET EMP_EMPLOYEE_ID="+empId+", EMP_FNAME='"+fName+"', EMP_LNAME='"+lName+"' WHERE EMP_EMPLOYEE_ID= ?";
stmt.executeUpdate(sql);
exists = true;
}
if(!exists)
{
String sql2 = "INSERT INTO [UAP].[dbo].[UAP_EMPLOYEE] (EMP_EMPLOYEE_ID, EMP_FNAME, EMP_LNAME ) VALUES (?,?,?)";
PreparedStatement prpStatement1 = conn.prepareStatement(sql2);
prpStatement1.setInt(1, Integer.parseInt(empId));
prpStatement1.setString(2, fName);
prpStatement1.setString(3, lName);
prpStatement1.execute();
prpStatement1.close();
}
%>
As EMP_EMPLOYEE_ID is an INTEGER field you will need to use:
prpStatementCheck.setInt(1, Integer.parseInt(empId));
Also, you can remove the quotes around this field for the UPDATE string:
String sql= "UPDATE [UAP_EMPLOYEE] SET EMP_EMPLOYEE_ID=" + empId + ", EMP_FNAME='" + fName+"', EMP_LNAME='" + lName + "' WHERE EMP_EMPLOYEE_ID= " + empId;
Again for prpStatement1:
prpStatement1.setInt(1, Integer.parseInt(empId));
I have a table inside consist of variable like Username, ContactNo, Date, Name.
And i would like to do a update for Username and ContactNo only to the original record in the database.
How can i make use of update sql statement to do it?
Below is my SELECT sql statement.
public void dbData(String UName)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/assignment","root","mysql");
ps = con.createStatement();
SQL_Str="Select username,numberOfBid from customer where username like ('" + UName +"')";
//SQL_Str="Select * from customer";
rs=ps.executeQuery(SQL_Str);
rs.next();
dbusername=rs.getString("username").toString();
dbbid=rs.getInt("numberOfBid");
//UName2 = rs.getString("username").toString();
UName2 = username;
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Exception Occur :" + ex);
}
}
http://dev.mysql.com/doc/refman/5.0/en/update.html
And please study...
Here is a quick and dirty solution: when you have modified your values, just add something like this
String updSQL = "udate table set numberOfBid = " + dbbid + " where user = " + UName;
ps.executeUpdate(updSQL);
There are however 1000 improvements you can make such using prepared statementsand placeholders:
String updSQL = "udate table set numberOfBid = ? where username like ?";
PreparedStatement pstmt = con.prepareStatement(updSQL);
pstmt.setInt(0, dbbid);
pstmt.setString(1, UName);
pstmt.execute();
May I suggest you to have a look at Hibernate, Spring JDBC, JPA... which are on a much higher level than JDBC is.