Connection Java with mysql Database

I'm sorry maybe this article is expired for professional programmer,hikz ..hikz....
but I'm sure for beginner programmer it's useful (maybe hikz.. hikz.. :D).

okay lest going to the topic .
I have experiences about this topic ,connection java with mysql database .
For this article I'm using netbean 6.0 for IDE,now lets begin.

First we must make new mysql database give name "test", after that we make table "user" and this is field2 that used.

id (integer),
name(string)
email(string)

okey this is the Sql sintact for make databse and table:

// Make database test

CREATE DATABASE test;

// Use test database to default schema

USE test;

// Make table user

CREATE TABLE user (

id int(11) NOT NULL,

name varchar(30) NOT NULL,

email varchar(30) NOT NULL,

PRIMARY KEY (id)

);

//Insert value of table user

INSERT INTO user VALUES
(1,'Mirza','Mirza-AT-yahoo-DOT-com'),
(2,'Mafis','Mafis-AT-yahoo-DOT-com'),
(3,'Dani','dani3610-AT-yahoo-DOT-com');

And now database is done,now open IDE netbean and make new project give name "test" ,after that make new package and give name "database".

after finish make new class and give name "user".

now klick right the project and choose library , and add library. From library menu , choose MySQL JDBC Driver, and push button add library and done.

now this is the code for user.java

package database;

// Import class for connection
import java.sql.*;

public class user {

public static void main (String[] args) throws SQLException {

// check driver mysql database
try{Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex){

System.out.println(ex);
System.exit(1);
}

//connection to mysql database

// For Db use your db name

//For user insert your db user and password is your db password
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db","user","password");
Statement statement =
conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = statement.executeQuery("SELECT * FROM user");


// Print data from the select statement
while(rs.next()){
System.out.println(rs.getString("id"));
System.out.println(rs.getString("name"));
}

}
}


and done.

note :* Statement ExecuteQuery just for the select statement and if you want insert,update or delete use ExecuteUpdate and give value Integer.

thank's DAn

Posted by Danivan7 | at Monday, September 22, 2008

0 comments: