如何建立Java程序与SQL数据库的连接?
1个回答
展开全部
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class BaseDao
{
//连接
private Connection conn = null;
//静态块
static
{
//实例化驱动类
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("SQL SERVER驱动装载失败");
e.printStackTrace();
}
}
//取得数据库连接
public Connection getConnection()
{
String url = "jdbc:sqlserver://localhost:1433;databaseName=FA";
String userName = "sa";
String userPwd = "";
try {
conn = DriverManager.getConnection(url, userName, userPwd);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("无法取得数据库连接");
e.printStackTrace();
}
return conn;
}
//关闭连接
public void closeConnection()
{
try
{
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("无法关闭数据库联接");
e.printStackTrace();
}
}
}
前提是导入sqlserver的jar包
import java.sql.DriverManager;
import java.sql.SQLException;
public class BaseDao
{
//连接
private Connection conn = null;
//静态块
static
{
//实例化驱动类
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("SQL SERVER驱动装载失败");
e.printStackTrace();
}
}
//取得数据库连接
public Connection getConnection()
{
String url = "jdbc:sqlserver://localhost:1433;databaseName=FA";
String userName = "sa";
String userPwd = "";
try {
conn = DriverManager.getConnection(url, userName, userPwd);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("无法取得数据库连接");
e.printStackTrace();
}
return conn;
}
//关闭连接
public void closeConnection()
{
try
{
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("无法关闭数据库联接");
e.printStackTrace();
}
}
}
前提是导入sqlserver的jar包
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询