This is my source code.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class DBConnect {
public static void main(String[] args) {
try {
String host = "jdbc:derby://localhost:1527/Employee";
String uName = "jayani";
String uPass = "jayani";
Connection con = DriverManager.getConnection(host, uName, uPass);
Statement stmt = con.createStatement();
String sql = "SELECT*FROM WORKERS";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id_col = rs.getInt("ID");
String fname = rs.getString("FIRST_NAME");
String lname = rs.getString("LAST_NAME");
String job = rs.getString("JOB_TITLE");
System.out.println(id_col + "" + fname + "" + lname + "" + job);
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
Here i got an exception like "executeQuery method can not be used for update."
What is this exception and how can I solve this.
Thank you.
You need to use executeQuery like this
Statement stmt = null;
String query = "select * from <tablename>";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
Related
I am trying to connect my HTML Login page with the database. I wrote this servlet but facing some error in the connection.
String name=request.getParameter("uname");//Passing the HTML tag to he string
String psw= request.getParameter("psw");//
String QUERY="SELECT *FROM login WHERE EMAIL=?,PASS=?"; //Query
Class.forName("com.mysql.jdbc.Driver");//Connection
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost/SmallERP", "root", "root")) {
PreparedStatement ps = con.prepareStatement(QUERY);
ps.setString(1, name);
ps.setString(2, psw);
try (ResultSet rs = ps.executeQuery()) {
if(rs.next()){
out.println("Done");
}else{
out.println("ERROR");
}
}
}
You have to use AND here. The modified query:
String QUERY="SELECT * FROM login WHERE EMAIL=? And PASS=?";
My Full Example is :-
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class GetUserDetailsUsingPS {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// read user entered data
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter email id:");
String id = scanner.nextLine();
System.out.println("User id=" + id);
System.out.println("Please enter password to get details:");
String pwd = scanner.nextLine();
System.out.println("User password=" + pwd);
printUserData(id, pwd);
}
private static void printUserData(String id, String pwd) throws ClassNotFoundException,
SQLException {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "select name, country, password from Users where email = ? and password = ?";
try {
con = DBConnection.getConnection();
ps = con.prepareStatement(query);
//set the parameter
ps.setString(1, id);
ps.setString(2, pwd);
rs = ps.executeQuery();
while (rs.next()) {
System.out.println("Name=" + rs.getString("name") + ",country="
+ rs.getString("country") + ",password="
+ rs.getString("password"));
}
} finally {
if (rs != null)
rs.close();
ps.close();
con.close();
}
}
}
I'm trying to run a query against a Sybase database. It seems like the connection is made successfully but when it hits rs.next() it fails to go to the first row in the results. It jumps down to the rs.Close().
I know for a fact that my query below works. I'm running it in a sql tool and it returns one record.
Please can someone tell me what I'm doing wrong?
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import com.sybase.jdbc4.jdbc.SybDataSource;
import com.sybase.jdbc4.jdbc.SybDriver;
public class test {
public static void main(String[] args) throws SQLException {
SybDriver sybDriver = null;
Connection conn = null;
Statement stmt = null;
String host = "123.12.34.56";
String url = "jdbc:sybase:Tds:"+host+":1300";
String username = "testuser";
String password ="password";
try{
sybDriver=(SybDriver)Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select top 1 brand, model,color,serialnum from myTable order by newid()");
while(rs.next())
{
String one = rs.getString(1);
String two = rs.getString(2);
String three = rs.getString(3);
String four = rs.getString(4);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
}
}
package com.java.bean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Dao {
// static Connection con = null;
static ResultSet rs = null;
static String url ="jdbc:mysql://localhost:3306/first";
static String user = "root";
static String passsword = "password";
public static Ex1 login(Ex1 ex){
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.driver");
Connection con = DriverManager.getConnection(url,user,passsword);
String userName = ex.getUserName();
String password = ex.getPassword();
Statement st = con.createStatement();
rs = st.executeQuery("Select * from employee where username = " +userName +"and password =" +password );
boolean more = rs.next();
if(!more)
{
System.out.println("you are not a registered user!");
ex.setValid(false);
}
else if(more)
{
System.out.println("welcome MR.HImanshu you are Great");
ex.setValid(true);
}
}
catch(Exception tex)
{
System.out.println("hey there is an exception " +ex);
}
return ex;
}
}
Is
Class.forName("com.mysql.jdbc.Driver");
not
Class.forName("com.mysql.jdbc.driver");
"Driver" with an uppercase "D".
I am trying to execute simple query using below DbQuery.java class which uses DbConnector to get a Connection from DriverManager.
note:
I have already included "mysql-connector-java-5.1.25-bin.jar" on my
classpath via: export
CLASSPATH=$CLASSPATH:/home/me/ocpjp/chapter-10/mysql-connector-java-5.1.25/mysql-connector-java-5.1.25-bin.jar
I am able to connect to mysql with "mysql -uroot -ptcial
addressBook", if it matters.
have also tried running with '-cp'
argument with no avail.
I am able to get my #3 DbConnect.java class to say "Database connection established".
Also #4 DbQueryWorking.java has no issues and provides expected output .
Can you please help me understand what is the issue here ?
1) DbConnector.java
package com.me.ocpjp.chapter10;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnector{
public static Connection connectToDb() throws SQLException{
String url = "jdbc:mysql//localhost:3306/";
String db = "addressBook";
String username = "root";
String password = "tcial";
return DriverManager.getConnection(url+db, username, password);
}
}
2) DbQuery.java
package com.me.ocpjp.chapter10;
import java.sql.Connection ;
import java.sql.Statement ;
import java.sql.ResultSet ;
import java.sql.SQLException ;
import com.me.ocpjp.chapter10.DbConnector;
public class DbQuery{
public static void main(String[] args){
try(Connection connection = DbConnector.connectToDb();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while(resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo") );
}
}catch(SQLException sqle){
sqle.printStackTrace();
System.exit(-1);
}
}
}
3) DbConnect.java
package com.me.ocpjp.chapter10;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbConnect{
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/";
String database = "addressBook";
String userName = "root";
String password = "tcial";
try(Connection connection = DriverManager.getConnection(url+database, userName, password)){
System.out.println("Database connection established");
}catch(Exception e){
System.out.println("Database connectioni NOT established");
e.printStackTrace();
}
}
}
4) DbQueryWorking.java
package com.me.ocpjp.chapter10;
import java.sql.Connection ;
import java.sql.Statement ;
import java.sql.ResultSet ;
import java.sql.SQLException ;
import java.sql.DriverManager;
public class DbQuery{
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/";
String database = "addressBook";
String userName = "root";
String password = "tcial";
try(Connection connection = DriverManager.getConnection(url + database, userName, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while(resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo") );
}
}catch(SQLException sqle){
sqle.printStackTrace();
System.exit(-1);
}
}
}
it looks like that the URL in DbConnector.java is wrong. A colon is missing. The url must be:
jdbc:mysql://localhost:3306/
and not
jdbc:mysql//localhost:3306/
your URL is wrong, you're missing a colon in it, it should be:
String url = "jdbc:mysql://localhost:3306/";
I have installed MYSQLSERVER 5.1.Then I installed mysql-connector-java-3.0.8-stable-bin.jar and put in drive c with folder core that is C:\core.Then in properties of computer I create user variable with variable name CLASSPATH and variable value:C:\core\mysql-connector-java-3.0.8-stable-bin.jar.
Now I have created database EMPLOYEE4
My java code is:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
class MySQLTest{
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query ="select count(*) from EMPLOYEE4 ";
Connection dbCon = null;
Statement stmt = null;
ResultSet rs = null;
//getting PreparedStatment to execute query
stmt = dbCon.prepareStatement(query);
//Resultset returned by query
rs = stmt.executeQuery(query);
while(rs.next()){
int count = rs.getInt(1);
System.out.println("count of stock : " + count);
}
} catch (Exception ex) {
ex.printStackTrace();
//Logger.getLogger(CollectionTest.class.getName()).log(Level.SEVERE, null, ex);
} finally{
//close connection ,stmt and resultset here
}
}
}
I get error that java.sql.SQLEXCEPTION:communication link failure:java.IO.Exception underlying cause:Unexpected end of input stream
You should be getting NPE. As you are executing your query on dbCon and not on dbcon
// initialize here
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query ="select count(*) from EMPLOYEE4 ";
// Null here
Connection dbCon = null;
// on dbCon which is null
stmt = dbCon.prepareStatement(query);
EDIT
This how your code suppose to look like.
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query = "select count(*) from EMPLOYEE4 ";
Statement stmt = dbcon.createStatement();
ResultSet rs = stmt.executeQuery(query);