Java database connection steps
As a newbie, I also spent some time figuring out this matter. The following describes the specific steps:
1. Software: database software (I use mysql) and java compiler eclipse.
2. Introduce mysql-connector-java-5.1.33-bin.jar in the project, which is in the Connector J folder under the mysql installation directory.
Right-click the project name-> build path-> add External Archives-> mysql-connector-java-5.1.33-bin.jar;
3. Open the mysql service and enter "net start mysql" in the command line (note that mysql is the service name and may be different sometimes. mysql57 is mine ),
You can also right-click "Task Manager-> service" or "Control Panel-> Administrative Tools-> service" to start the instance manually.
4. Familiar with basic database commands. I will not go into details here.
5. Write and run the java code:
Import java. SQL. connection; import java. SQL. driverManager; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; public class mysqlTest {public static void main (String [] args) {new mysqlTest (). start ();} public void start () {String driver = "com. mysql. jdbc. driver "; String url =" jdbc: mysql: // 127.0.0.1: 3306/mybase "; // mybase is the database name String user =" root "; String password =" r Ootpassword "; try {Class. forName (driver). newInstance (); // try to connect to the database Connection conn = DriverManager. getConnection (url, user, password); if (! Conn. isClosed () System. out. println ("Succeeded connecting to the Database! "); // Compile the database Statement statement Statement = conn. createStatement (); String SQL = "select * from IDinformation"; ResultSet rs = statement.exe cuteQuery (SQL); String name = null; while (rs. next () {name = rs. getString ("id"); System. out. println (name + "\ t" + rs. getString ("secret");} rs. close (); conn. close ();} catch (ClassNotFoundException e) {System. out. println ("Sorry, can't find the Driver! "); E. printStackTrace ();} catch (SQLException e) {e. printStackTrace ();} catch (Exception e) {e. printStackTrace ();}}}
6. Everyone's computer environment and software are different. Don't try to do things right once. Try more.
Steps 2nd and 3 and code compilation are prone to problems.