Monday, August 13, 2012

how can we connect java to mysql database connection

Using JDBC to connect to MySQL from Java Program




This sample Java program connects to MySQL database using JDBC, executes a query and retrieves and prints the value of the database field.

This same sample code can be used to connect to any type of database, all you need to do is change the connection url (dbUrl in the sample). For this code to work properly, you will need to download the mysql driver for JDBC in other words Java Connectors from mysql.com site.

If after downloading the URL it still doesn't work then it is probably due to the classpath. You will have to add the driver jar file in the classpath.
 
(यह नमूना जावा प्रोग्राम MySQL के डेटाबेस JDBC का उपयोग करने के लिए जोड़ता है, एक क्वेरी और retrives के कार्यान्वित और डेटाबेस फ़ील्ड का मूल्य मुद्रित करता है.

यह एक ही नमूना कोड डेटाबेस के किसी भी प्रकार से कनेक्ट करने के लिए इस्तेमाल किया जा सकता है, तुम सब करने की ज़रूरत कनेक्शन यूआरएल (नमूना में dbUrl) बदल रहा है. इस कोड ठीक से काम करने के लिए, आप JDBC के लिए अन्य जावा कनेक्टर्स शब्दों में mysql.com साइट से MySQL चालक डाउनलोड की आवश्यकता होगी.

यदि URL को डाउनलोड करने के बाद यह अभी भी तो नहीं काम करता है यह शायद classpath के कारण. आप classpath में ड्राइवर जार फ़ाइल जोड़ने के लिए होगा.
)

 

import java.sql.*;
import javax.sql.*;

public class jdbcdemo{

public static void main(String args[]){
String dbtime;
String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
String dbClass = "com.mysql.jdbc.Driver";
String query = "Select * FROM users";

try {

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
dbtime = rs.getString(1);
System.out.println(dbtime);
} //end while

con.close();
} //end try

catch(ClassNotFoundException e) {
e.printStackTrace();
}

catch(SQLException e) {
e.printStackTrace();
}

}  //end main

}  //end class

No comments:

Post a Comment