发一下牢骚和主题无关:
1、首先将sqljdbc4.jar驱动文件,放置项目文件夹的lib下面(自行下载)。
package DataBase;
import java.sql.*;
public class SqlserverConn {
public Connection conn;
public Statement st;
public ResultSet rs;
//获得链接
public Connection getConn() throws SQLException, ClassNotFoundException
{
String driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://localhost:1433;databaseName=MyServer"; //:1433为数据库默许端口号,MyServer为数据库名字
String password = "sa"; //登录用户名
String user = "sa"; //登录密码
try {
Class.forName(driverClassName);
conn = DriverManager.getConnection(url, user, password);
System.out.println("数据库连接成功");
} catch (SQLException ex1)
{
System.out.println("数据库连接失败");
}
return conn;
}
//关闭链接
public void Close() throws SQLException
{
rs.close();
st.close();
conn.close();
}
//返回执行行数
public int update(String sql) throws ClassNotFoundException
{
int result=0;
try
{
getConn();
st = conn.createStatement();
result=st.executeUpdate(sql);
}catch(SQLException ex)
{
System.out.print("失败"+ex);
}
return result;
}
//返回结果集
public ResultSet query(String sql) throws ClassNotFoundException
{
try{
getConn();
st = conn.createStatement();
rs=st.executeQuery(sql);
}catch(SQLException ex1)
{
System.out.println("失败"+ex1);
}
return rs;
}
//返回结果集行数
public int getTableRows(String sql) throws SQLException, ClassNotFoundException
{
int count =0;
try{
getConn();
st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery(sql);
rs.last();
count = rs.getRow();
}
catch(SQLException ex)
{
System.out.println("失败"+ex);
}
return count;
}
//测试连接方法
public static void main(String[] args) throws SQLException, ClassNotFoundException
{
int count =0;
SqlserverConn sq = new SqlserverConn();
String sql = "select * from userinfo";
count = sq.getTableRows(sql);
System.out.println(count);
sq.Close();
}
}
文章结束给大家分享下程序员的一些笑话语录:
PC软件体积大,是因为一个PC软件功能往往较多,能够满足你一个方面的需求,而一个iphone软件往往没几行代码,干一件很小的事情,自然需要的软件就多。就像吃西瓜和吃瓜子的来比数目,单位不同啊。
---------------------------------
原创文章 By
sql和数据库
---------------------------------