Uploaded by sunilsth12345

database

advertisement
Example to connect to the mysql
database in java
we need to know following
informations for the mysql database:
Steps to interact with the database in java
•
•
•
•
•
Register/load the driver class
Creating connection
Creating statement
Executing queries
Closing connection
• Driver class: The driver class for the mysql
database is com.mysql.jdbc.Driver.
• Connection URL: The connection URL for the
mysql database
is jdbc:mysql://localhost:3306/zaved where jdbc
is the API, mysql is the database, localhost is the
server name on which mysql is running, we may
also use IP address, 3306 is the port number and
zaved is the database name
• Username: The default username for the
mysql database is root.
• Password: Password is given by the user at the
time of installing the mysql database.
Example
•
•
•
•
•
•
•
•
•
•
•
•
•
•
// Register or Load the Driver class
Class.forName("com.mysql.cj.jdbc.Driver");
// Creating connection
conn = DriverManager.getConnection(dbURL, username, password);//if we write
here Connection conn then itwill be a local variable
// creating statement
PreparedStatement ps=conn.prepareStatement("select * from march_stu where
id=?");
ps.setInt(1, 5);
// execute query
ResultSet rs=ps.executeQuery();
while(rs.next()){
// System.out.println(rs.getString("id") + " " + rs.getString("location") );
System.out.println(rs.getString(1) + " " + rs.getString(2)+" "+rs.getString(3)+"
"+rs.getString(4)+" "+rs.getString(5) );
}
PreparedStatement interface
public int executeUpdate()----executes the query. It is used for create, drop, insert, update,
delete etc.
public ResultSet executeQuery()-----executes the select query. It returns an instance of ResultSet.
……
Note..Statement
interface also uses these
methods and do the same job.
Download