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();
}
}
}