SQL Server 2005 Database Connection code
Package test;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.SQLException;
Defines the class that connects the database Dbutil
public class Dbutil {
Defines a method that returns a value of connection object used to establish a connection to the database
public static Connection getconnection () {
Create a Connection object to connect to the database
Connection Con=null;
try {
//? load the database driver. The JVM loads the program-driven class named Net.sourceforge.jtds.jdbc.Driver when executing this code driver
This class (Driver) is loaded, and it is registered in the DriverManager.
Class.forName () Creates an object using the principle of reflection, which is popularly said: Get the class specified in the string parameter and initialize the class
//?class.forname () links to knowledge http://blog.csdn.net/u013003837/article/details/27334601
Class.forName ("Net.sourceforge.jtds.jdbc.Driver");
//localhost is the connection IP of the database, if it is local database write localhost or 127.0.0.1, 1433 is SQL Server database
The server port that is occupied; No_one is the database name
Final String url= "Jdbc:jtds:sqlserver://localhost:1433/no_one";
//user name of login database
Final String username= "sa";
//password for login database
Final String userpassword= "sa123";
try {
? Create a connection to a database
To connect to a database, you need to request and obtain a connection object from Java.sql.DriverManager, which represents a connection to a database
Use the DriverManager getconnectin (String url,string username,string Password) method to pass in the specified desired
The path of the connected database, the user name of the database, and the password to obtain
//? Connection is an interface, DriverManager is an ordinary class, the getconnection () method is a static method, they can be used
= Connected, because the getconnection () method returns an instance of a class that implements the connection interface.
Con=drivermanager.getconnection (URL, username,userpassword);
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
Returns the database connection object that was established
return con;
}
}
public static void Main (string[] args) {
Dbutil db=new dbutil ();
Connection connection=db.getconnection ();
SYSTEM.OUT.PRINTLN ("Connection Successful! ");
System.out.println (connection. GetClass (). GetName ());
}
}
Operation Result:
PS: The database jar package download link for this document address: http://download.csdn.net/detail/u013003837/7412787
Link to MySQL database connection address: http://blog.csdn.net/u013003837/article/details/27338083