We have to follow 6 steps to play with MySql database in java jdbc.
Note: We have use “mysql-connector-java-version-bin.jar” ex- mysql-connector-java-5.0.3-bin.jar
Step 1: Create table in database
CREATE TABLE ‘USER_DETAILS’ (
‘USER_ID’ INT(5) NOT NULL,
‘USER_NAME’ VARCHAR(50) NOT NULL,
‘PASSWORD’ VARCHAR(50) NOT NULL,
PRIMARY KEY(‘USER_ID’)
) ;
Step 2: Load the Driver class
“com.mysql.jdbc.Driver” using below syntax –
Note: We have use “mysql-connector-java-version-bin.jar” ex- mysql-connector-java-5.0.3-bin.jar
Step 1: Create table in database
CREATE TABLE ‘USER_DETAILS’ (
‘USER_ID’ INT(5) NOT NULL,
‘USER_NAME’ VARCHAR(50) NOT NULL,
‘PASSWORD’ VARCHAR(50) NOT NULL,
PRIMARY KEY(‘USER_ID’)
) ;
Step 2: Load the Driver class
“com.mysql.jdbc.Driver” using below syntax –
Class.forName("com.mysql.jdbc.Driver");
Step 3: Get connection by using below url –
"jdbc:mysql://localhost:3306/databasename","username","password"
"jdbc:mysql://localhost:3306/databasename","username","password"
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","username","password");
Step 4: Create Statement or PreparedStatement –
PreparedStatement prepareStatement = connection.prepareStatement("SELECT * FROM USER_DETAILS");
Step 5: Execute the query-
ResultSet resultSet = prepareStatement.executeQuery();
Step 6: Iterate the result set-
while (resultSet.next()) { System.out.println("UserName:"+resultSet.getString("NAME") + "," + ("UserPassword:"+resultSet.getString("PASSWORD")); }
Example-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import java.sql.*; class MySqlTest { public static void main(String[] args)throws Exception { Class.forName("com.mysql.jdbc.Driver "); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename", "username", "password"); PreparedStatement prepareStatement = connection.prepareStatement("SELECT * FROM USER_DETAILS"); ResultSet resultSet = prepareStatement.executeQuery(); while (resultSet.next()) { System.out.println("UserName:"+resultSet.getString("NAME")+ "," +("UserPassword:"+ resultSet.getString("PASSWORD") ); } resultSet.close(); prepareStatement.close(); connection.close(); } } |
No comments :
Post a Comment