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/";
Related
I am working in command prompt this is my code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnf) {
System.out.println("Driver could not be loaded: " + cnf);
}
}
public static void main(String[] args)
{
String connectionUrl = "jdbc:mysql://localhost:3306/mysql";
String dbUser = "root";
String dbPwd = "admin";
Connection conn;
ResultSet rs;
String queryString = "SELECT ID, NAME FROM exptable";
try {
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
Statement stmt = conn.createStatement();
// INSERT A RECORD
stmt.executeUpdate("INSERT INTO exptable (name) VALUES (\"TINU K\")");
// SELECT ALL RECORDS FROM EXPTABLE
rs = stmt.executeQuery(queryString);
System.out.println("ID \tNAME");
System.out.println("============");
while (rs.next()) {
System.out.print(rs.getInt("id") + ".\t" + rs.getString("name"));
System.out.println();
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException sqle) {
System.out.println("SQL Exception thrown: " + sqle);
}
}
}
i am getting error like
java.lang.ClassNotFoundException and java.sql.SQLException
so may i know what mistake have i made
You might have missed the classpath in your java command. While executing from command prompt you must mention the class path along with your command.
java -cp
ex:
java -cp /home/test/jars:/home/test/src com.test.Lab
While executing update by jdbc on Oracle dbms, my program hangs. I think it is waiting for another process/user to release lock on the rows or table that I am trying to update. So what are the possible causes for this problem and how can I solve it?
I am making calls to the dbms through jdbc as show here:
public static void updateEmployee(String name,int id) throws ClassNotFoundException
{
Connection con=null;
PreparedStatement st=null;
String driver= "oracle.jdbc.driver.OracleDriver";
String username="someuser";
String password="pwd";
String url="jdbc:oracle:thin:#hostname:1521:ORAJAVADB";
Class.forName(driver);
try
{
con=DriverManager.getConnection(url,username,password);
st=con.prepareStatement("update employee set employeeName=? where
employeeId = ? ");
st.setString(1,name);
st.setInt(2,id);
st.executeUpdate();
st.close();
con.close();
}
catch(SQLException ex)
{
}
}
I made this code for update function using java with oracle database. I hope it will help you. Good Luck
package updatemethod;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import oracle.jdbc.pool.OracleDataSource;
public class UpdateMethod {
public static String url = "jdbc:oracle:thin:#mohammed:1521:XE";
public static String user = "md";
public static String password = "md";
public static String query;
public static Connection conn;
public static Statement smt = null;
// CREATE DATABASE CONNECTION
public static void getDBConnection() throws SQLException{
OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(url);
conn = ds.getConnection(user, password);
System.out.println("DataBase Accessed!");
}
public static void updateEmployee(String nID, String newFirst, String newLast, String newJob)throws SQLException{
try{
smt = conn.createStatement();
smt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = smt.executeQuery("SELECT ID, FIRSTNAME, LASTNAME, JOB FROM MD.EMPLOYEE1");
while(uprs.next()){
int newID = Integer.parseInt(nID);
uprs.updateInt("ID", newID);
uprs.updateString("FIRSTNAME", newFirst);
uprs.updateString("LASTNAME", newLast);
uprs.updateString("JOB", newJob);
uprs.updateRow();
System.out.println("DataBase Updated\n");
System.out.println("ID " + newID + " " + "FIRSTNAME " + newFirst + " " + "LASTNAME " + newLast + " " + "JOB " + newJob);
}
}
catch(SQLException er){
System.out.println(er);
}
}
public static void main(String[] args) throws SQLException {
// CREATE CONNECTION BY CALLING getDBConnection();
getDBConnection();
// NOW, CALL OUR updateEmployee(String,String,String,String) FUNCTION
updateEmployee("123", "mohammed", "Jamal", "Computer Technique Engineer");
}
}
I have added JAR file "mysql-connector-java-5.1.36-bin" and have created database "UserScore" and under that table "ScoreSheet".I have added a row in ScoreSheet (Name,Score) value ('Kamal',40) to verify but the code throws a lot of exceptions on connection.I am using Eclipse + Xampp.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class SQLDriver{
public static void main(String[] args){
try{
//Accessing driver from jar file
Class.forName("com.mysql.jdbc.Driver");
//Get connection through creating a variable 'myConn'
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/UserScores");
//Create statement
PreparedStatement statement = myConn.prepareStatement("select * from 'scoresheet'");
//Execute SQL Query
ResultSet result = statement.executeQuery();
//Process the result set
while(result.next()){
System.out.println(result.getString(1)+" "+result.getString(2));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
I always do it like this:
// Hostname
private static final String dbHost = "127.0.0.1";
// Port -- Standard: 3306
private static final String dbPort = "3306";
// Database name
private static String database = "database"; //
// Database user
private static final String dbUser = "root";
// Datenbankpasswort
private static final String dbPassword = "";
private Statement s;
public void Connect() {
try {
Class.forName("java.sql.Driver"); // load driver
Connection conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":"
+ dbPort + "/" + database + "?" + "user=" + dbUser + "&"
+ "password=" + dbPassword); // try to connect with your attributes
s = conn.createStatement();
} catch (ClassNotFoundException e) { //
l.error("Driver not found " + e);
} catch (SQLException e) {
l.error("Connect not possible" + e);
}
}
Your query should specify Scoresheet without '
Specify the username and password when calling DriverManager.getConnection
The second row in your table does not appear to be of type string. Invoke result.getInt(2) rather than result.getString(2)
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 using cassandra-jdbc to perform the operation on data in cassandra but when i run this simple program i get exception.
this is my code:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.*;
import javax.sql.*;
public class Operations
{
public static void main(String[] args){
try
{
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://localhost:9160/temp");
String qry = "select name FROM cql";
Statement smt = con.createStatement();
ResultSet resultSet = smt.executeQuery(qry);
System.out.println(resultSet);
while(resultSet.next())
{
System.out.println(resultSet);
}
}
catch(Exception e)
{
System.out.println(" : "+e.getMessage());
}
}
}
i got :cannot parse 'name' as hex bytes
Try:
import static org.apache.cassandra.utils.Hex.bytesToHex;
...
String name = bytesToHex("name".getBytes());
String qry = "select '" + name + "' FROM cql";