Java has been officially started. On the first day, we will start with the function. First study how to connect to MySQL using Java
Code
| The Code is as follows: |
Copy code |
|
Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. Statement;
Import java. SQL. ResultSet;
Public class MyTest {
Public static void main (String args []) {
Connection con = null;
Try {
// Obtain the MySQL-driven instance
Class. forName ("com. mysql. jdbc. Driver"). newInstance ();
// Provide the address username and password and obtain the connection object
Con = DriverManager. getConnection ("jdbc: mysql: // 127.0.0.1/test", "root", "123456 ");
If (! Con. isClosed ())
// Connection success prompt
System. out. println ("Successfully connected to MySQL server using TCP/IP ...");
// Create a Statement with a Connection object
Statement st = con. createStatement ();
// Run the SQL statement to read
ResultSet rs = st.exe cuteQuery ("SELECT * FROM emlog_blog ");
// Read data cyclically
While (rs. next ()){
// Print data
System. out. println (rs. getString ("gid "));
}
// Close
Con. close ();
} Catch (Exception e ){
System. err. println ("Exception:" + e. getMessage ());
}
}
} |
Note that
The com. mysql. jdbc. package needs to be downloaded from MySQL.
:
Http://dev.mysql.com/downloads/connector/j/
After downloading the package, add the package to the libary of Eclipse to run the code above.