So I'm trying to connect my java code to mysql and when I run the code below nothing prints out not even the error. I'm following a YouTube tutorial and understand everything except where he is getting "jdbc:mysql:" from. Any help would be awesome thanks.
package ztestconnection;
import java.sql.*;
public class Test {
static String Username = "Klongrich";
static String Password = "********";
static String Connection = "jdbc:mysql://localhost:8080/hospital";
public static void main(String [] args){
Connection con = null;
try{
con = DriverManager.getConnection(Connection, Username, Password);
System.out.println("Connected");
} catch(Exception e){
System.out.println(e);
}
}
To connect java application with the mysql database mysqlconnector.jar file is required to be loaded.
1:- Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
//STEP 1. Import required packages
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Before you can open a connection, you need to load the specific driver class, like so:
try
{
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception ex)
{
// handle the error
}
This ensures that java.sql.DriverManager can find the driver class definition.
There's some good example code in the MySQL Connector/J documentation.
As for the jdbc:mysql: part of the DSN (Data Source Name), that's a standard syntax that tells the driver manager and the database that they're opening a JDBC connection to a MySQL database. It will be explained in the Oracle Java documentation.
And Tim has a good point about your variable names. Don't give a variable the same name as a class. Even if it doesn't confuse the compiler, it'll confuse the hell out of the maintenance programmer (you) about a week from now.
Related
I am trying to connect to mysql on my laptop. using the code I have pasted below. I have added the CLASSPATH containing the full path of the file:
mysql-connector-java-5.1.37-bin.jar
and exported it.But I get persistently the mentioned error. Can somebody tell me, please, what I am missing that makes me to get this error message form my machine.
My machine is Fedora core 21, I am trying to execute the code under the user, and not root, and this is the code i am using and of course the static final variables "user" and "password" are not empty strings as they are here:
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";
// Database credentials
static final String USER = "";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connect ion
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
I have really tried to include any related information that i could guess it is related. If more information is needed to answer the question I am willingly ready to provide.
the DB_URL should set the port and the database name of MySQL.
just like(windows):
jdbc\:mysql\://111.202.27.131\:3306/bridgeResultDatabase?characterEncoding\=utf8
Here bridgeResultDatabaseis the mysql database name, it works for me.
Hope it helps.
There are some mistakes above.
Update(I try in my windows and using root of mysql in Linux):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public static void main(String[] args) throws ClassNotFoundException, SQLException{
String JDBC_DRIVER="com.mysql.jdbc.Driver";
String DB_URL="jdbc:mysql://192.168.11.52/mysql";
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL,"root","111111");
Statement statement = conn.createStatement();
String hrappSQL = "CREATE DATABASE testDatabase";
statement.executeUpdate(hrappSQL);
}
And I create the database "testDatabase" successfully in my linux mysql.
I have been trying this for a few hours now but with no success. I downloaded the JDBC driver and it shows that it is one of my referenced libraries under my Package Explorer in Eclipse but every time I try to run my code I get errors. My database is fine as I can change it and view it from the MySQL Command Line Client.
I actually followed a guides directions on how to do it, only replacing the information from their database to information about mine.
import java.sql.*;
public class FirstExample {
//JDBC Driver Name and Database URL
final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final static String DB_URL = "jdbc:mysql://localhost/test_database";
//Database Credentials
static final String USER = "user_one";
static final String PASS = "User_one_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
//Open a Connection
System.out.println("Connecting to the Database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Execute a Query
System.out.println("Creating Statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM user";
ResultSet rs = stmt.executeQuery(sql);
//Extract Data from Result Set
while (rs.next()) {
//Retrieve by Column Name
int id = rs.getInt("id");
String first = rs.getString("name");
//Display Values
System.out.print("ID: " + id);
System.out.println("Name: " + first);
}
//Clean Up Environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
//Handle Errors For JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle Errors for Class.forName
e.printStackTrace();
} finally {
//Finally Block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
//Nothing We Can Do
}
try {
if (conn != null)
conn.close();
} catch (Exception se) {
se.printStackTrace();
}//End Finally Try
}//End Try
System.out.println("Goodbye!");
}//End Main
}//End First Example
Here is the error I get http://pastebin.com/hLSxV3aq
I'm trying to teach myself how to connect to a msaccess database in java.
I have set up a class to access the database as follows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
Then I have my code which is just trying to select everything from the table.
I have created the table in msAccess and the code seems to get through the connect method in the above code without any problems, indicating it is finding the database and accessing it somewhat. The problem happens when I call the prepareStatement using the connection, i.e. code line:
stm = conn.prepareStatement(sql);
The full code is:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: \t \t" + id);
System.out.println("Name: \t \t" + name);
System.out.println("Gender: \t" + gender);
System.out.println("Address: \t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
You are receiving the error because when you try to call .prepareStatement the connection is closed. Your AccessDBConnect2 class contains a finally block that closes the connection before it returns. Fix that class so it leaves the connection open.
By the way, the JDBC-ODBC Bridge has been removed from Java 8 and is effectively obsolete. You might be interested in this alternative:
Manipulating an Access database from Java without ODBC
I've removed the obviously incorrect answer :) another possibility:
I would think the issue is in your connection to the database, try changing 'C:/Users/Bridget/Documents/EmployeeSys.accdb' to 'C:\\Users\Bridget\Documents\EmployeeSys.accdb'
i am using my following code in eclipse using derby database,but getting the error as
Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:322)
at java.sql.DriverManager.getConnection(DriverManager.java:273)
at jdbc.JDBCSample.main(JDBCSample.java:19)."
package jdbc;
import java.sql.*;
public class JDBCSample {
public static void main( String args[]) {
String connectionURL = "jdbc:derby://127.0.0.1:8080/SAMPLE";
// Change the connection string according to your db, ip, username and password
try {
// Load the Driver class.
Class.forName("org.apache.derby.jdbc.ClientDriver");
// If you are using any other database then load the right driver here.
//Create the connection using the static getConnection method
Connection con = DriverManager.getConnection (connectionURL);
//Create a Statement class to execute the SQL statement
Statement stmt = con.createStatement();
//Execute the SQL statement and get the results in a Resultset
ResultSet rs = stmt.executeQuery("select moviename, releasedate from movies");
// Iterate through the ResultSet, displaying two values
// for each row using the getString method
while (rs.next())
System.out.println("Name= " + rs.getString("moviename") + " Date= " + rs.getString("releasedate"));
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
}
}
}
I think your problem will be solved, if you
call getConnection("..", "..", "..") method with username and password.
Example
Connection con = DriverManager.getConnection(connectionURL, "sa", "sa");
I am creating a desktop application, in which I have to log in into SQL Server 2005 on the remote machine and have to create a database, User etc. By using jTDS I am able to create a connection to the database as well as able to execute "SELECT" commnads but not able to execute database commands like- create database, create user etc.
Here is my test code:
public class Test {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "net.sourceforge.jtds.jdbc.Driver";
static final String DB_URL = "jdbc:jtds:sqlserver://10.96.11.31:1433;useNTLMv2=true;domain=myDomain";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL);
//STEP 4: Execute a query
System.out.println("Creating database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
If you need to create a DB via JDBC then the you'll need a user with permissions to connect to the master database on that server. Create a java.sql.Connection object to the master database then simply create the Statement and execute the SQL:
"CREATE DATABASE MyDB"
I'm a little confused by the question, so I apologize if I misinterpreted it.