1. Connect to SQL Server
Package org.test01.utils;
Import java.sql.*;
public class Dbutil {
/*
* Connections to various databases
*/
Connect to SQL Server
public static String Driver = "com.microsoft.sqlserver.jdbc.SQLSeriverDriver";//Connection Driver
public static String URL = "jdbc://localhost:1433;databasename= database name";//
public static String uid = "";//user name
public static String upwd = "";//user password
static {
try {
Class.forName (driver);
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
public static Connection getconnection () {
Connection conn = null;
try {
conn = Drivermanager.getconnection (URL,UID,UPWD);
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}//here is the URL, user name, password
Return conn;//back to Conn
}
Close Resource
public static void Close (ResultSet rs,statement stmt,connection conn) {
if (rs!=null) {
try {
Rs.close ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
if (stmt!=null) {
try {
Stmt.close ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
if (conn!=null) {
try {
Conn.close ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Test if the connection is healthy
public static void Main (string[] args) {
System.out.println (getconnection ());
}
}
2. Connecting to MySQL is the same.
The driver is converted to string driver = "Com.mysql.jdbc.Driver";
URL is jdbc:mysql://:127.0.0.1; database name;
The following user and password are the user name and password of your database, as shown above
There are several database connections in the back, not written on
Connection to the Java database