Java 连接SQLserver

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Database
{ //数据库连接方式是混合验证方式

public String sqlserverDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String sql="select * from location";
Connection con = null;   //连接数据库
Statement st = null;     //创建对象,用来执行不带参数的SQL查询和更新
PreparedStatement pre = null;//创建对象,用来执行带参数的SQL语句
public ResultSet rs = null;//存放结果集

public  Connection getConnection() //创建对象的时候已经连接数据库
{  
	try
	{
		Class.forName(sqlserverDriver);
		this.con = DriverManager.getConnection("jdbc:sqlserver://localhost:1434;"+"DatabaseName=user","sa","98515");
		this.st = this.con.createStatement();
		this.rs = st.executeQuery(sql);
		
	}
	catch(Exception e)
	{
		System.out.println(e.toString());
	}
	return con;
}

public ResultSet executeQuery(String strsql) //查询记录
{
	try 
	{
		this.rs = st.executeQuery(strsql);
		return rs;
	}
	catch(Exception e) 
	{
		e.printStackTrace();
		return null;
	}
}

public boolean execute(String strsql) //添加数据
{
	try 
	{
		if(this.st.executeUpdate(strsql) == 0)
			return false;
		else
			return true;
	}
	catch(SQLException e) 
	{
		e.printStackTrace();
		return false;
	}
}

}

你可能感兴趣的:(Java 连接SQLserver)