connect java application to mysql server in netbeans 6.8
i am beginner in java as well as in netbeans .please give me complete procedure how i can connect my j开发者_JAVA技巧ava application to mysql to insert data .
Download "mysql-connector-java-5.1.13-bin.jar" from following link http://sqlworkbench.mgm-tp.com/viewvc/trunk/sqlworkbench/junit/mysql-connector-java-5.1.13-bin.jar?revision=2294&pathrev=2294
Following is a sample java code to connect to a mysql database and retrieve data from a table.
In below code database name is "databaseName"
and table name is "userTable"
Dont forget to add "mysql-connector-java-5.1.13-bin.jar" to your netbeans project's libraries.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class NewClass {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://127.0.0.1:3306/";
String dbName = "databaseName";
Statement stmt = null;
ResultSet result = null;
String driver = "com.mysql.jdbc.Driver";
String databaseUserName = "root"; //user name to connect to database(plz change it with your mysql username)
String databasePassword = "root"; //password to connect to database(plz change it with your mysql password)
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, databaseUserName, databasePassword);
stmt = conn.createStatement();
result = null;
String password,username;
result = stmt.executeQuery("select * from userTable ");
if(!result.isBeforeFirst()){
System.out.println("resultset contin no rows");
}else{ // result set contain some data.... ie.. table contain some rows
// process data
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Netbeans' knowledge base article describing how to connect to a mysql database.
精彩评论