In this program we create table in MYSQL using "create" statement and insert data using "insert " statement query in the created database.
In this program we create table in MYSQL using "create" statement and insert data using "insert " statement query in the created database.CREATION OF TABLE,INSERTION &DISPLAY OF DATA USING SQL QUERY
In this progam we create table in MYSQL using "create" statement and insert data using "insert " statement query in the created database. Before running this java code you need to paste "mysql-connector-java-3.1.6-bin.jar" file in the jdk1.6.0_01\lib.
testquery.java
import java.sql.*; class testQuery { public static void main(String[] args) { try { //URL of the database(ankdb) String connectionURL = "jdbc:mysql://192.168.10.13:3306/ankdb"; // declare a connection by using Connection interface Connection connection = null; // declare object of Statement interface that uses for //executing sql statements. Statement statement = null; // declare a resultset that uses as a table // for output data from the table. ResultSet rs = null; int updateQuery = 0; // Load JDBC driver "com.mysql.jdbc.Driver". Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(connectionURL, "root", "root"); statement = connection.createStatement(); // sql query of string type to create a data base. String QueryString = "CREATE TABLE user1 (User_Id INTEGER NOT NULL AUTO_INCREMENT, " + "User_Name VARCHAR(25), UserId VARCHAR(20),User_Pwd VARCHAR(15), primary key(User_Id))"; updateQuery = statement.executeUpdate(QueryString); // sql query to insert values in the specified table. QueryString = "INSERT INTO user1(User_Name,UserId,User_Pwd) VALUES ('Mahendrak',"+ "'mahendra25','1213456')"; updateQuery = statement.executeUpdate(QueryString); if (updateQuery != 0) { System.out.println("table is created successfully and " + updateQuery + " row is inserted."); } // sql query to retrieve values from the specified table. QueryString = "SELECT * from user1"; rs = statement.executeQuery(QueryString); while (rs.next()) { System.out.println(rs.getInt(1) + "" + rs.getString(2) + "" + rs.getString(3) + "" +rs.getString(4)+"\n"); } // close all the connections. rs.close(); statement.close(); connection.close(); } catch (Exception ex) { System.out.println("Unable to connect to batabase."); } } }
output--