To connect to a mysql database we need the following details about the database. Driver class- driver class for mysql which is " ...
To connect to a mysql database we need the following details about the database.
- Driver class-driver class for mysql which is "com.mysql.jdbc.Driver".
- Connection URL-connection url looks like "jdbc:mysql://localhost:3306/pointofsale where jdbc is the API ,mysql is database type ,localhost is the server name which may also be ip address where the mysql database is running and 3306 is the port number and pointofsale database name
- username-default username for mysql server is root
- password- password is given by the user when installing the mysql database.
Example code for connecting to mysql database in java
Before running below code,ensure you have mysql server installed in your computer.Create database pointofsale.
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class DbConnection {
public Connection con;
DbConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/pointofsale","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from users");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "
+ ""+rs.getString(4)+" "+rs.getString(5)+" "
+ ""+rs.getString(6));
con.close();
{
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
new DbConnection();
}
}