Example:
String s1;
String q = "select * from EntryByTitle where booktitle='"+s1+"'";
here in query statement why +s1+ is used in the syntax. As s1 is string, so it should be '"s1"'. But why '"+s1+"' is written in project.
Use a PreparedStatement and a bind parameter. This usually takes the form
String q = "select * from EntryByTitle where booktitle=?";
String bookTitle = "";
Connection conn = null;
try {
try (PreparedStatement ps = conn.prepareStatement(q)) {
ps.setString(1, bookTitle);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("booktitle"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Related
I want my function to return the result of the Select statement, but in instead it prints SQLServerResultSet:1. How do I do to print/return the data in my function?
My function should execute the SQL statement and store the result in a variable.
public ResultSet selectSubmissions(int department) {
Connection connection = Database.getConnection();
String sql = "SELECT * FROM [MyDB_Widget].[dbo].[surveys] INNER JOIN [MyDB_Widget].[dbo].[instructors] ON surveys.instructor_id = instructors.instructor_id Where instructors.department_id = 2;";
ResultSet rs = null;
try {
Statement statement = connection.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
rs.getString(1); //or rs.getString("column name");
}
} catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
return rs;
}
hi my program work in back ground and show different message from database
in specific time the problem always show the same row
//////
**upload code **
public void myMethod(){
long startTime = System.currentTimeMillis();
int counter = 0;
while(true) {
if((System.currentTimeMillis() - startTime ) == 5000){
try{
String host = "jdbc:derby://localhost:1527/Quet";
String uName = "eenas";
String uPass= "2234";
con = DriverManager.getConnection( host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery( "SELECT * from EENAS.EENAS");
rs.next();
int id_col = rs.getInt("ID");
String id =Integer.toString(id_col);
String me=rs.getString("MESSAGE");
System.out.print(me);
rs.close();
}
catch(SQLException err)
{
JOptionPane.showMessageDialog(null, err);
}
startTime = System.currentTimeMillis();
continue; }
else{ continue; } } }
upload code
the can solve this problem by using arrayList to save all data, your program now show only that last one because they change their value every time, the solution like this,
public void DoConnect( ) {
try{
String host = "jdbc:derby://localhost:1527/Quet";
String uName = "eenas";
String uPass= "2234";
con = DriverManager.getConnection( host, uName, uPass);
stmt = con.createStatement();
rs = stmt.executeQuery("select * from EENAS.EENAS");
List<String> PMessage = new ArrayList<String>();
List<Integer> id_col = new ArrayList<Integer>();
while(rs.next()){
id_col.add(rs.getInt("ID"));
PMessage.add(rs.getString("MESSAGE"));
jTextArea1.setText(PMessage);
}
rs.close();
stmt.close();
con.close();
}
catch(SQLException err)
{
JOptionPane.showMessageDialog(null, err);
}
}
I didn't run the code on my machine but this is the logic can solve the problem.
I want to retrieve all the name and the number of row from MySQL to java. So far I only able to retrieve the total row number but I only get the last name. What's wrong here ?
StaffManagement.java
adminAPI api= new adminAPI();
try {
int num= api.displayCheckBoxAndLabel();
String allName= api.displayName();
System.out.println(num+allName);
}
adminAPI
public int displayCheckBoxAndLabel() throws Exception // get the number of row
{
int count = 0;
String sql="Select count(*) AS adminID from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
count= rs.getInt("adminID");
}
ps.close();
rs.close();
conn.close();
return count ;
}
public String displayName() throws Exception // get all the name
{
String name = null;
String sql="Select name from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
name= rs.getString("name");
}
ps.close();
rs.close();
conn.close();
return name ;
}
You currently return a single String, and your method iterates all of the admin names (but terminates after the final row, so that's your result). Instead, build a List of names and return that. You could also use a try-with-resources close to close your Connection, Statement and ResultSet instances. Something like
public List<String> displayName() throws Exception // get all the name
{
String sql = "Select name from admin";
List<String> names = new ArrayList<>();
DatabaseConnection db = new DatabaseConnection();
try (Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString("name"));
}
}
return names;
}
This might be helpful
private String names[];
int i = 0;
while (rs.next()) {
names[i] = rs.getString("name");
i++;
}
Then you can use a for loop to return each name in StaffManagement.java
I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}
I am getting an exception like as
java.sql.SQLException: Before start of result set when calling getInt() method
My code is as follows:::
public void setdateTOSource(){
try{
String q = "SELECT * FROM ipp.resource;";
ResultSet result = DB_Access.getData(q);
System.out.println("Size result set"+result.getFetchSize());
while(result.next()){
getIpSource().add(result.getString(1));
System.out.println(result.getString(1));
}
System.out.println("source size "+getIpSource().size());
}
catch(Exception e){
System.out.println(e);
}
}
public void insertTargetToDb(List<String> targetValue){
try{
Connection con = DB_Connect.getDataBaseConnection();
Statement statement1 = con.createStatement();
int val=0;
String q1 = "SELECT MAX(area_id) as aa FROM ipp.area;";
ResultSet resultset = statement1.executeQuery(q1);
if(resultset.next()){
val = resultset.getInt(1);
};
val++;
String q2 = "INSERT INTO ipp.area VALUES("+val+",'"+getAreaName()+"',1);";
Statement statement2 = con.createStatement();
statement1.executeUpdate(q2);
for( int y=0;y<targetValue.size();y++){
System.out.println("FS");
String ip=targetValue.get(y);
System.out.println("ip" +ip);
String q3 ="SELECT resource_id FROM ipp.resource r where ip_address like '"+ip+"%';";
Statement statement3 = con.createStatement();
ResultSet resultset3 =statement3.executeQuery(q3);
System.out.println("FS1");
// ResultSet result1 =DB_Access.getData(q3);
System.out.println("FS2");
System.out.println("result set"+resultset3.getFetchSize());
//====================================================================
while(resultset3.next()){
setId(resultset.getInt(1));
}
System.out.println("result :........."+resultset3.getInt("resource_id"));
System.out.println("FS3");
String q4 = "INSERT INTO ipp.used_resource VALUES("+val+","+getId()+");";
Statement statement4= con.createStatement();
statement4.executeUpdate(q4);
// DB_Access.setData(q3);
statement3.close();
statement4.close();
// resultset3.close();
}
resultset.close();
statement1.close();
statement2.close();
con.close();
addMessage("Area created Successfully");
}
catch(Exception e){
System.out.println(e);
}
}
Exception comes after line
//==========================
resource_id is an integer value
This line
while(resultset3.next()){
setId(resultset.getInt(1));
}
must be replaced with?
while(resultset3.next()){
setId(resultset3.getInt(1));
}