It is convenient to connect to the MySql server using Jdbc.
First, import jdbc to the project or put jdbc into ClassPath. Here, I use Eclipse to directly import the jdbc jar file.
Then, the DriverManager is developed, And the froName of the Class is directly completed using the simplest method. The Code is as follows:
Class. forName ("com. mysql. jdbc. Driver"). newInstance ();
Then, instantiate a Connection. Pay attention to the user name and password. There are several methods to choose from. Here I use the getConnection (String url, String user, String password) method of the DirverManager class. Specific Use: DriverManager
For example: Connection conn = DriverManager. getConnection ("jdbc: mysql: // localhost/mydatabase", "root", "1234 ");
Next, create a Statement for executing the SQL Statement. This is easy to do with one line of code:
Statement stat = conn. createStatement ();
Finally, you can use the stat instance to execute SQL statements. For details, refer to Statement.
Sample Code:
The created mydatabase contains a mytable table that contains an integer id and a text content.
Use the following code to view the content of the first 20 rows in mytable.
- PackageCom. tobacco. mysqltest;
- ImportJava. SQL. Connection;
- ImportJava. SQL. DriverManager;
- ImportJava. SQL. ResultSet;
- ImportJava. SQL. SQLException;
- ImportJava. SQL. Statement;
- Public ClassMain {
- Private StaticConnection conn;
- Private StaticStatement stat;
- Private StaticResultSet rs;
- Public Static VoidMain (String [] args ){
- Try{
- Class. forName ("Com. mysql. jdbc. Driver"). NewInstance ();
- System. out. println ("Load jdbc successfully");
- }Catch(InstantiationException e ){
- // TODO Auto-generated catch block
- E. printStackTrace ();
- }Catch(IllegalAccessException e ){
- // TODO Auto-generated catch block
- E. printStackTrace ();
- }Catch(ClassNotFoundException e ){
- // TODO Auto-generated catch block
- E. printStackTrace ();
- }
- Try{
- Conn = DriverManager. getConnection ("Jdbc: mysql: // localhost/mydatabase","Root","1234");
- Stat = conn. createStatement ();
- IntN =20;
- IntI =1;
- While(I <n ){
- Rs = stat.exe cuteQuery ("SELECT * FROM mytable WHERE id ="+ I );
- If(Rs! =Null){
- Rs. first ();
- String content = rs. getString (rs. findColumn ("Content"));
- System. out. println (content );
- }
- I ++;
- }
- }Catch(SQLException e ){
- // TODO Auto-generated catch block
- E. printStackTrace ();
- }
- }
- }