1. java怎麼連接sqlserver資料庫
java中使用jdbc連接sql server資料庫步驟:
1.JDBC連接SQL Server的驅動安裝 ,前兩個是屬於資料庫軟體,正常安裝即可(注意資料庫登陸不要使用windows驗證)
<1> 將JDBC解壓縮到任意位置,比如解壓到C盤program files下面,並在安裝目錄里找到sqljdbc.jar文件,得到其路徑開始配置環境變數
在環境變數classpath 後面追加 C:\Program Files\Microsoft SQL Server2005 JDBC Driver\sqljdbc_1.2\enu\sqljdbc.jar
<2> 設置SQLEXPRESS伺服器:
a.打開SQL Server Configuration Manager -> SQLEXPRESS的協議 -> TCP/IP
b.右鍵單擊啟動TCP/IP
c.雙擊進入屬性,把IP地址中的IP all中的TCP埠設置為1433
d.重新啟動SQL Server 2005服務中的SQLEXPRESS伺服器
e.關閉SQL Server Configuration Manager
<3> 打開 SQL Server Management Studio,連接SQLEXPRESS伺服器, 新建資料庫,起名字為sample
<4> 打開Eclipse
a.新建工程-> Java -> Java project,起名為Test
b.選擇eclipse->窗口->首選項->Java->installed JRE 編輯已經安裝好的jdk,查找目錄添加sqljdbc.jar
c.右鍵單擊目錄窗口中的Test, 選擇Build Path ->Configure Build Path..., 添加擴展jar文件,即把sqljdbc.jar添加到其中
<5> 編寫Java代碼來測試JDBC連接SQL Server資料庫
import java.sql.*;
public class Test {
public static void main(String[] srg) {
//載入JDBC驅動
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//連接伺服器和資料庫sample
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=sample";
String userName = "sa"; //默認用戶名
String userPwd = "123456"; //密碼
Connection dbConn;
try {
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
System.out.println("Connection Successful!"); //如果連接成功 控制台輸出
} catch (Exception e) {
e.printStackTrace();
}
}
}
執行以後就可以連接到sample資料庫了。
2. java如何連接SQLserver資料庫
從M$網站下載最新JDBC驅動或都使用maven:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>9.4.1.jre11</version>
</dependency>
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionUrl =
"jdbc:sqlserver://yourserver.database.windows.net:1433;"
+ "database=AdventureWorks;"
+ "user=yourusername@yourserver;"
+ "password=yourpassword;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "loginTimeout=30;";
String insertSql = "INSERT INTO SalesLT.Proct (Name, ProctNumber, Color, StandardCost, ListPrice, SellStartDate) VALUES "
+ "('NewBike', 'BikeNew', 'Blue', 50, 120, '2016-01-01');";
ResultSet resultSet = null;
try (Connection connection = DriverManager.getConnection(connectionUrl);
PreparedStatement prepsInsertProct = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);) {
prepsInsertProct.execute();
// Retrieve the generated key from the insert.
resultSet = prepsInsertProct.getGeneratedKeys();
// Print the ID of the inserted row.
while (resultSet.next()) {
System.out.println("Generated: " + resultSet.getString(1));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
}
}