0

i am beginner in java as well as in netbeans .please give me complete procedure how i can connect my java application to mysql to insert data .

2 Answers 2

1

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();
    }
}
}
2
  • Be careful when posting copy and paste boilerplate/verbatim answers to multiple questions, these tend to be flagged as "spammy" by the community. If you're doing this then it usually means the questions are duplicates so flag them as such instead: stackoverflow.com/a/11920142/419
    – Kev
    Aug 12, 2012 at 13:10
  • Above answer is correct for this question too ... that's why i pasted it here too... Aug 13, 2012 at 5:23
0

Netbeans' knowledge base article describing how to connect to a mysql database.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.