我寫大致步驟,每個步驟的具體做法,可以自行百度
1、 安裝好SQLServer數據庫、eclipse
2、 配置SQLServer的IP和端口號,這個可以上網搜,配置SQLServer爲sa登錄
3、 在SQLServer數據中創建yq數據庫,在yq數據庫中創建yq_user數據表,當然,名字可以自己起,在代碼中注意改正就行
4、 下載安裝JDBC驅動驅動
完成之後會出現一個文件夾,如下
5、 在Java中新建ConnetDB項目,項目中新建Test2類,導入上圖中文件
只能導入一個,不然會出錯
6、 Test2代碼:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test2
{
publicstatic void main(String[] args)
{
//Create a variable for the connection string.
StringconnectionUrl = "jdbc:sqlserver://localhost:1433;" +"databaseName=AdventureWorks;integratedSecurity=true;";
Stringurl ="jdbc:sqlserver://192.168.1.140:1433;databaseName=yq;user=sa;password=123";//sa身份連接
//Declare the JDBC objects.
Connectioncon = null;
Statementstmt = null;
ResultSetrs = null;
try
{
//Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con= DriverManager.getConnection(url);
//Create and execute an SQL statement that returns some data.
StringSQL = "SELECT TOP 10 * FROM yq_user";
stmt= con.createStatement();
rs= stmt.executeQuery(SQL);
//Iterate through the data in the result set and display it.
while(rs.next())
{
System.out.println(rs.getString(4)+ " " + rs.getString(6));
}
}
//Handle any errors that may have occurred.
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(rs != null)
try
{
rs.close();
}catch (Exception e)
{
}
if(stmt != null)
try
{
stmt.close();
}catch (Exception e)
{
}
if(con != null)
try
{
con.close();
}catch (Exception e)
{
}
}
}
}
鏈接方式有集成和使用sa身份鏈接,體現在使用的鏈接字符串中,這裏使用的是sa鏈接,建議也使用,不然會很麻煩。