How to connect MySQL with Java? - java

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);

Related

Sybase jdbc4 not returning any results from sql query

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) {
}
}

JDBC programming

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

inserting values into mysql table using jdbc

Values inserted using program are not seen in database. the following is the code which I used for the same
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBC {
private static Scanner sc;
public static void main(String args[]) throws Exception {
sc = new Scanner(System.in);
System.out.println("hii");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/rsystems", "root", "rsystems");
PreparedStatement stmt = con.prepareStatement("insert into user valiues(?,?)");
System.out.println("Enter id:");
int no = sc.nextInt();
System.out.println("Enter name:");
String name = sc.next();
stmt.setInt(1, no);
stmt.setString(2, name);
//I think I need to commit over here and I have tried the same but even with that I didn't see my inserted data in database
}
}
You've wrong query in your PreparedStatement
PreparedStatement stmt = con.prepareStatement("insert into user (id, name) values(?,?)");
You query is wrong and you are never executing it.
PreparedStatement stmt = con.prepareStatement("insert into user values(?,?)");
stmt.execute();
Maybe you can use try..catch help you to find the mistake you make just a wrong word
You are not executing your query inside preparedStatement. Also make sure you have valid SQL.
You can use PreparedStatement.executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
Try
PreparedStatement stmt = con.prepareStatement("insert into user values(?,?)");
stmt.executeUpdate();
From maintenance point of view, we specify order of columns in insert query like.
insert into user (id, name) values(?,?)
Commit:
You can check your database configuration about autoCommit. If by default autoCommit is true then you can omit commiting in your code else you will have to commit it manually in your code. Like
con.commit();
Connection close:
You should close your statements and connection when they are no longer required.
stmt.close();
connection.close();
Note: Don't forget to handle/throw Exceptions throws from all these methods such as SQLException.
public static void main(String args[]) {
String dbURL = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "root";
try {
Connection conn = DriverManager.getConnection(dbURL, username, password);
if (conn != null) {
System.out.println("Connected");
}
String sql = "INSERT INTO Users (id, password,) VALUES (?, ?)";
PreparedStatement statement;
statement = conn.prepareStatement(sql);
statement.setInt(1, 1);
statement.setString(2, "admin");
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A Record inserted successfully!");
}
} catch (SQLException e) {
System.out.println("Exception occured" + e);
}
}
After setting value need PreparedStatement executed
Look at below
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class JDBC {
private static Scanner sc;
public static void main(String args[]) throws Exception {
sc = new Scanner(System.in);
System.out.println("hii");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rsystems", "root", "rsystems");
PreparedStatement stmt = con
.prepareStatement("insert into user valiues(?,?)");
System.out.println("Enter id:");
int no = sc.nextInt();
System.out.println("Enter name:");
String name = sc.next();
stmt.setInt(1, no);
stmt.setString(2, name);
stmt.execute();//You have to execute this statement
// I think I need to commit over here and I have tried the same but even
// with that I didn't see my inserted data in database
}
}
This works:
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBC {
private static Scanner sc;
public static void main(String args[]) throws Exception {
sc = new Scanner(System.in);
System.out.println("hii");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/rsystems", "root", "rsystems");
PreparedStatement stmt = con.prepareStatement("insert into user values(?,?)");
System.out.println("Enter id:");
int no = sc.nextInt();
System.out.println("Enter name:");
String name = sc.next();
stmt.setInt(1, no);
stmt.setString(2, name);
stmt.executeUpdate();
}
}

get a database connection in java

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);

java.lang.ClassNotFoundException Netbeans java derby

I use Netbeans, doing a java app. I created a class ConnectDB for db connetion using Java DB in netbeans. i started the server and ten conneted to db. when i run the file it produce
java.lang.ClassNotFoundException: org.apache.derby.jdbc.ClientDriver # 25 line
and
java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/Libraryprj;create=true
#30 th line of code
the code is below
package Lms;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
/**
*
* #author JOJO
*/
public class ConnectDB {
static Connection conn;
public static void main(String[] args) {
String driver = "org.apache.derby.jdbc.ClientDriver";
String connectionURL = "jdbc:derby://localhost:1527/Libraryprj;create=true";
String createString = "CREATE TABLE Employee (NAME VARCHAR(32) NOT NULL, ADDRESS VARCHAR(50) NOT NULL)";
try {
Class.forName(driver);
} catch (java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(connectionURL);
Statement stmt = (Statement) conn.createStatement();
stmt.executeUpdate(createString);
PreparedStatement psInsert = conn.prepareStatement("insert into Employee values (?,?)");
psInsert.setString(1, args[0]);
psInsert.setString(2, args[1]);
psInsert.executeUpdate();
Statement stmt2 = (Statement) conn.createStatement();
ResultSet rs = stmt2.executeQuery("select * from Employee");
int num = 0;
while (rs.next()) {
System.out.println(++num + ": Name: " + rs.getString(1) + "\n Address" + rs.getString(2));
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
get this library
http://repo.maven.apache.org/maven2/org/apache/derby/derbyclient/10.9.1.0/derbyclient-10.9.1.0.jar
and copy it to Derby's libs folder.
If you use Tomcat download derbyclient.jar from here . And copy the jar file to Tomcat's lib folder.

Categories