Java connects to MySQL database Java connects to SQL Server database

In Java applications, we often perform necessary operations on the database. Next, we'll learn how to use java to connect to MySQL database and SQL Server database

1、 Mysql

  import java. sql. Connection;  import java. sql. DriverManager;  import java. sql. ResultSet;  import java. sql. SQLException;  import java. sql. Statement;

public class TestOne {

private static Connection connection; private static Statement statement; private static ResultSet result;

Public static void main (string [] args) {try {/ / load jdbc driver class. Forname ("com. Mysql. JDBC. Driver"); / / indicate the host name (default: 127.0.0.1), port number (default: 3306) and database name (must be specified) string url = "JDBC: mysql://localhost:3306/test1 "; / / establish a connection with the database. Connection = drivermanager.getconnection (URL," root "," 123456 "); / / create a statement object and send the SQL statement to the database. Statement = connection. Createstatement(); / / return the query result to result. Result = statement. ExecuteQuery (" select * from user "); while (result. Next()) {system. Out. Println (" Name: "+ result. GetString (1) + " password:" + result. getString(2)); } connection. close(); result. close(); statement. close(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { if(connection != null) connection.close(); if(result != null) result.close(); if(statement != null) statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /**

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>