Steps for creating a table and inserting data into it in MySQL database have been give here. Initially MySQL should be started in XAMPP control panel. In command prompt, mysql should be started in the path of mysql bin. Database is created followed by Table creation and data is inserted into table via command prompt. Mysql connector jar file is required for the execution of the connectivity code in java that is added to the classpth. MySqlTest.java file presents the connectivity code for database. It initially loads the diver (“com.mysql.jdbc.Driver”) and creates the connection with the database using DSN (“user”) and url as local host and port number as 3306. Then statement object is created for the established connection that executes the query (“select”) mentioned and produces the result of query execution (ResultSet).
import java.sql.*;
class MySqlTest {
public static void main(String args[]) {
String url = "jdbc:mysql://slogix.in:3306/";
String dbName = "user";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String dbpassword = "root";
try {
// loading driver
Class.forName(driver);
// Connection set up with database named as user
Connection c = DriverManager.getConnection(url+dbName,userName,dbpassword);
// Creating statement for the connection to use sql queries
Statement st = c.createStatement();
// Executing sql query using the created statement over the table user_details located in the database pointing by the dsn
ResultSet rs = st.executeQuery("SELECT * from user_details");
// Accessing the result of query execution
while(rs.next())
{
String username = rs.getString(1);
System.out.println(username);
}
// Closing the statement and connection
st.close();
c.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}