how to link java and mysql - java

I created a database from the command line and wrote Java code to access the database. My code prints an error on execution. Can anyone tell me how to connect the JDBC driver with Java?
import java.sql.*;
class Test{
public static void main(String arg[]){
try{
String query="select * from photo ";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/mydb","user","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
rs.next();
String sname=rs.getString(2);
System.out.println(sname);
con.close();
}
catch(Exception e)
{
System.out.println("error ");
}
}
}

First of all remove the space at the end of the query
String query="select * from photo ";
Next try giving the port in the url
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
Finally as you said its giving you java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
you need to add the mysql-connector.jar in your classpath.Get the jar from here
Well if you are using command prompt you can run like this
java -cp .;completePathOfMysqlConnector/mysql-connector-java-5.1.6.jar className
If you are using elipse then download the jar and add it to the classpath like this
Right click on the project -> properties ->java build path ->switch to libraries tab -> add external jar then select the jar and ok you are done

1>it seems that SQL port is not assigned (default is 3306) in "jdbc:mysql://localhost"
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
2> should download and add mysql-connector-java to library
Hope this would help

Related

How to establish connection between Java Program and Database without using IDE/ External Tools?

I want to write a Java Program for Establishing Connection between Java Program and Database, but I don't want to use any IDE like Netbeans, Eclipse, Visual Studio, XAMP, etc. I have jar files for Driver of required DBMS.
public class JDBCDemo
{
public static void main(String args[])
{
try
{
/**
* Steps for Establishing Connection between Java Application and Database
*/
//1. Load and Reginster Driver
Class.forName("com.mysql.jdbc.Driver");
//2. Establish a connection between Java Application and Database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/practicals", "root", "root123");
//3. Create Statement Object
Statement st = con.createStatement();
//4. Send and Execute SQL queries
ResultSet rs = st.executeQuery("SELECT * FROM tushar");
//5. Process the result from ResultSet object
while(rs.next())
{
System.out.println(rs.getString(1));
}
//6. Close the Connection
con.close();
}
catch(Exception e)
{
System.out.println(e.toString().trim());
}
}
}
It is showing error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
How to Establish connection ??
You need to add the mysql driver jar in the classpath before you run the program.
There are various ways to do so.
javac -cp "JAR_PATH" ClassName.java
java -cp "JAR_PATH" ClassName
Add the jar file in C:\Program Files\Java\\jre\lib\ext
set classpath=PATH_TO_JAR;
colon(:) is compulsory after jar file name
Compilling Program
javac -cp mysql-connector.jar: ProgramFileName.java
javac -cp mysql-connector.jar: JDBCDemo.java
Running Program
java -cp mysql-connector.jar: ProgramFileName
java -cp mysql-connector.jar: JDBCDemo
Note:- Simillar can be applied while using other jar files for performing other operations.
Sample Output

Java JDBC JTDS test connection string

I have an application using JTDS to connect to SQL Server. I need to change the database and want to test the connection string first before reconfiguring the application. I'm a SQL Server DBA, not a Java developer!
Here's my test code:
// Import the SQL Server JDBC Driver classes
import java.sql.*;
class Example
{
public static void main(String args[])
{
try
{
// Build the connection string, and get a connection
System.out.println("1.");
System.out.println("2.");
String connectionUrl = "jdbc:jtds:sqlserver://UK-SB-Server:53569;DatabaseName=helpdesk;user=helpdesk;password=MyPwd;Tds=8.0;PrepareSql=3;XaEmulation=false";
System.out.println("3.");
Connection con = DriverManager.getConnection(connectionUrl);
System.out.println("Connected.");
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT * from dbo.AllowedValues";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next())
{
System.out.println(rs.getString(1) + " " + rs.getString(2));
}
}
catch(Exception e)
{
System.out.println("Error - " + e.getMessage());
System.exit(0);
}
}
}
I compile it with:
C:\Progra~1\Java\jdk1.6.0_45\bin\javac C:\JavaTest\example.java
I run it with:
C:\Progra~1\Java\jdk1.6.0_45\bin\java -classpath C:\JavaTest Example
jtds-1.2.jar and Example.class are both in C:\JavaTest
I get the following error:
1.
2.
3.
Error - No suitable driver found for jdbc:jtds:sqlserver://UK-SB-Server:53569;DatabaseName=helpdesk;user=helpdesk;password=MyPwd;Tds=8.0;PrepareSql=3;XaEmulation=false
I've read conflicting posts as to whether I need
Class.forName("net.sourceforge.jtds.jdbc.Driver");
or not. If I put the line between println("1.") and println("2."), it just fails earlier with
1.
Error - net.sourceforge.jtds.jdbc.Driver
I may be missing something obvious, but please help me resolve this issue.
You appear to be facing two issues:
Issue 1. It seems that jTDS 1.2 is sufficiently old that you actually do need to call
Class.forName("net.sourceforge.jtds.jdbc.Driver");
before you try to establish the connection.
Issue 2. When you specify the classpath, you need to explicitly include the jTDS jar file. That is, this won't work ...
C:\JavaTest>"\Program Files\Java\jdk1.6.0_45\bin\java.exe" -cp C:/JavaTest Example
1.
Error - net.sourceforge.jtds.jdbc.Driver
... but this works for me:
C:\JavaTest>"\Program Files\Java\jdk1.6.0_45\bin\java.exe" -cp C:/JavaTest;C:/JavaTest/jtds-1.2.jar Example
1.
2.
3.
Connected.
...
Lets break down steps, run following commands from cmd:
cd C:\JavaTest
set path=C:\Progra~1\Java\jdk1.6.0_45\bin
javac example.java
java -cp .;jtds-1.2.jar -Djdbc.drivers=net.sourceforge.jtds.jdbc.Driver Example
The last line will load the driver manually, so no need to change code.
Problem is that you need to register driver before making connections to database.
I've read conflicting posts as to whether I need
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Yes, but you have to place it before line
Connection con = DriverManager.getConnection(connectionUrl);

JDBC no suitable driver found just on Linux? [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed last month.
I am trying to write a program to connect to a MySQL database in eclipse, but I get the error "java.sql.SQLException: No suitable driver found".
The java code is:
import java.sql.*;
public class FirstExample {
//static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String S_DB_URL = "jdbc:mysql://localhost:3306/emp";
static final String S_USER = "root";
static final String S_PASS = "root";
public static void main(String[] args) {
try {
System.out.println("Connecting to database...");
//Class.forName(S_JDBC_DRIVER);
Connection connection = DriverManager.getConnection(S_DB_URL,
S_USER, S_PASS);
System.out.println("Creating statement...");
Statement statement = connection.createStatement();
String sql = "SELECT * FROM Employee";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int iId = resultSet.getInt("id");
int iAge = resultSet.getInt("age");
String sFirst = resultSet.getString("fname");
String sLast = resultSet.getString("lname");
System.out.print("ID: " + iId);
System.out.print("\tAge: " + iAge);
System.out.print("\tFirst: " + sFirst);
System.out.println("\tLast: " + sLast);
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException se) {
for (Throwable t : se) {
t.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
The output in the console tab is:
Connecting to database...
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/emp
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at FirstExample.main(FirstExample.java:21)
Goodbye!
I have used the MySQL Connector/J. It is unzipped in the MySQL installation directory and the jar file is added to the CLASSPATH.
Also refer to this image. There is an ! mark at the project root.image01
I get the error as in the next image: image02 when I include the 2 commented statements:
static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
Class.forName(S_JDBC_DRIVER);
For all but the most trivial applications the CLASSPATH environment variable is NOT used. Normally the libraries are include in the Class-Path entry in the manifest of the jar, or in the -cp option of the java commandline.
In this case you need to add the MySQL JDBC driver to the buildpath of your Eclipse project.
I had the same problem. I solved it by adding:
Class.forName("com.mysql.jdbc.Driver");
you can place the path like java -cppwd/mysql-connector-java-5.1.22-bin.jar:. <classname>.
make sure that your in same directory where the mysql driver is .
Hope that helps .
Load Driver class just before getting the connection.
Use this code:
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "user", "passw");
Alternatively you can also add the installed jar file to your eclipse project by selecting the project in eclipse, right click it and go down to properties, select the Java Build Path>>select the Libraries Tab>>Add external jar file and browse for the installed mysql-connector-java.jar file or any mysql java connector file int the /usr/share/java/ directory for most ubuntu users. Click okay and rebuild your project. Good luck
I encountered the same problem as you, but I handled it as follows:
I copied the jar, which is called mysql-connector-java-5.1.23-bin.jar, into the \Apache Software Foundation\Tomcat 6.0\lib, and restarted tomcat.
Hope that helps

Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I wanted to print the contents in a database but whenever I run this program I got this error saying that
Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
SQL exception occuredjava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mydatabase
I have installed MySQL from this link http://dev.mysql.com/downloads/windows/installer/ its a 248mb file and installed completely. I can access my database within MySQL but can't able to access from netbeans. I separately downloaded the mysql-connector-java-5.1.4.jar and set the CLASSPATH but now also I got this error.
import java.sql.*;
public class jdbcResultSet {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydatabase","root",
"root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT * FROM employee");
System.out.println("id name job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
}
catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}
First Check can you import import com.microsoft.sqlserver.jdbc.SQLServerDriver;
if it say com.microsft can not be resolved to a type that means u have to add your jar files to java build path and after that to deployment path from project properties.
java build path
Right click on project=>Properties=>Java Build Path=>
Librariess=>ADD External Jar file
deployment path
Right click on project=>Properties=>Deployment Assembly=>
ADDs=>Java Build Path Entries==> mssql_jdbc
The CLASSPATH environment variable is only used by the java.exe command and even then only when used without any of the -cp, -classpath, -jar arguments. It is ignored by IDEs.
So if you are running the application from your IDE place the mysql-connector.jar in your IDE's classpath
I downloaded the mysql-connector-java-5.1.4.jar file and placed in "C:\Program Files\MySQL\Java Connector" directory and edit System Environment Variable from control panel then set CLASSPATH as C:\Program Files\MySQL\Java Connector
Add the jar file, not the directory that the jar file is in.
Instead of,
C:\Program Files\MySQL\Java Connector
the CLASSPATH should include,
C:\Program Files\MySQL\Java Connector\mysql-connector-java-5.1.4.jar

Java connectivity with PostgreSQL

Can someone please tell me how to connect java file to postgresql database (if possible with code n explanation)
Google is a good start
http://jdbc.postgresql.org/
Here is an example test.java
import java.sql.*;
class test
{
public static void main(String[] args) {
String hostname="", dbname="", username="", password="";
try {
int argno = 0;
hostname = args[argno++];
dbname = args[argno++];
username = args[argno++];
password = args[argno++];
} catch (Exception ex) {
System.err.println("Usage: java -cp driver.jar:. test [hostname] [dbname] [username] [password]");
System.exit(1);
}
try {
Class.forName("org.postgresql.Driver");
Connection connection =
DriverManager.getConnection(
"jdbc:postgresql://"+hostname+"/"+dbname,
username,
password
);
ResultSet rs = connection.createStatement().executeQuery(
"select version() as version"
);
while ( rs.next() ) {
System.out.println(rs.getString("version"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Download a current driver from JDBC download page, compile this and run like this on Unices:
java -cp [driver_file_name].jar:. test [hostname] [dbname] [username] [password]
On Windows:
java -cp [driver_file_name].jar;. test [hostname] [dbname] [username] [password]
Just wanted to expound on Tometzky's answer for other beginners using the Netbeans IDE in UNIX like me.
I want the driver to be recognized as a library in the IDE. If you go to Tools->Libraries, you will see the current list. Hit "New Library" and type "PostgreSQL JDBC Driver" or whatever name you want to give it. Then in the Classpath tab, hit "Add JAR/Folder" and point to where you've saved your downloaded driver. I'm not sure if there is a "correct" place to store it, I think it rather depends on how you back up your system and if multiple users share it. Somewhere in your home directory is fine.
After that, make a new project of type "Java Application" and paste Tometzky's code into main. In your project tree, right click on Libraries and add the JDBC driver directly to the project. Now you don't have to worry about specifying the driver on the command line.
Build your project and head over to its "dist" folder. Now you can run it with the command
java -jar myprojectname.jar 127.0.0.1 [dbname] [user] [pw]
That of course assumes you are connect to the database server on your own machine. [user] and [pw] refer to your PostgreSQL username and pw.
Also, when you download the documentation it comes as a bunch of html files. Save them somewhere and point your browser to the index.html file (in Firefox it is File-->Open File).

Categories