
怎么用jdbc连接sqlserver数据库查询数据
JDBC连接SQL Server的驱动安装 ,前两个是属于数据库软件,正常安装即可(注意数据库登陆不要使用windows验证)
<1> 将JDBC解压缩到任意位置,比如解压到C盘program files下面,并在安装目录里找到sqljdbcjar文件,得到其路径开始配置环境变量
在环境变量classpath 后面追加 C:\Program Files\Microsoft SQL Server2005 JDBC Driver\sqljdbc_12\enu\sqljdbcjar
<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,查找目录添加sqljdbcjar
c右键单击目录窗口中的Test, 选择Build Path ->Configure Build Path, 添加扩展jar文件,即把sqljdbcjar添加到其中
<5> 编写Java代码来测试JDBC连接SQL Server数据库
select from on convert(int,aid)=bid 或者select from on cast(aid as int)=bid
或者select from on aid =cast(bid as varchar(1000)) 建议用最后一个 因为你那个字段是字符型的话,有可能被输入乱七八糟的东西导致转换失败,把int型转换成varchar型会好很多
这种方法并不是很常用,只是页面的相关 *** 作,代码太多,所以中间省略了部分<%
Object userUID=sessiongetAttribute("USERID");
String uid="";
if(userUID!=null)
{
uid=(String)userUID;
}
else
{ responsesendRedirect("/Public/loseSessionjsp");}
try
{
String today=DateUtilsgetInstance()getToday();
String userIP=requestgetRemoteAddr();
String sql="";
String getPage=requestgetParameter("toPage");
sql=cuexchange(requestgetParameter("sql")); if (sql==null||sqlequals("")){
String getDepId="";
String getPoliticalPosition="";
String getTechnicalPosition="";
String getPoliticalLevel="";
String getTechnicalLevel="";
String getDegreeCode="";
String getGrade="";
String getLongevity="";String getAllowance="";
long depId=0;
long degreeCode=0;
long politicalPosition=0;
long technicalPosition=0;
long politicalLevel=0;
long technicalLevel=0;
long grade=0;
long longevity=0;
long allowance=0;
String[] postID=null;
String post="";
String userID="";
String userName="";
String address="";
getDepId=requestgetParameter("depId");
depId=LongparseLong(getDepIdtrim());getDegreeCode=requestgetParameter("degreeCode");
if (getDegreeCode!=null) {
degreeCode=LongparseLong(getDegreeCodetrim());
}
getPoliticalPosition=requestgetParameter("politicalPosition");
if (getPoliticalPosition!=null) {
politicalPosition=LongparseLong(getPoliticalPositiontrim());
}
post=requestgetParameter("post");
if(post!=null&&posttrim()equals("1"))
postID=requestgetParameterValues("dyourlocation");
getTechnicalPosition=requestgetParameter("technicalPosition");if (getTechnicalPosition!=null) {
technicalPosition=LongparseLong(getTechnicalPositiontrim());
}
getPoliticalLevel=requestgetParameter("politicalLevel");if (getPoliticalLevel!=null) {politicalLevel=LongparseLong(getPoliticalLeveltrim());
}getTechnicalLevel=requestgetParameter("technicalLevel");if (getTechnicalLevel!=null) {
technicalLevel=LongparseLong(getTechnicalLeveltrim());
}getGrade=requestgetParameter("grade");if (getGrade!=null) {
grade=LongparseLong(getGradetrim());
}getLongevity=requestgetParameter("longevity");if (getLongevity!=null) {
longevity=LongparseLong(getLongevitytrim());
}getAllowance=requestgetParameter("allowance");
if (getAllowance!=null) {
allowance=LongparseLong(getAllowancetrim());
}
userID=ParamUtilsgetParameter(request,"userID");//用户代码
userName=ParamUtilsgetParameter(request,"userName");
//用户名称
address=ParamUtilsgetParameter(request,"address");
//得到要转入的页面sql="select org_user from org_user,org_detail where org_useruser_id=org_detailuser_id";
if (depId!=0)
{
sql=sql+" and org_userdepartment_id="+depId+"";
}if (userID!=null&&userID!=""){
sql=sql+" and org_useruser_id='"+userID+"'";
}
if (userName!=null&&userName!="")
{
sql=sql+" and org_username like '%"+userName+"%'";
}if (address!=null&&address!="")
{
sql=sql+" and org_useraddress like '%"+address+"%'";
}
if(post!=null&&!posttrim()equals("0"))
{
sql=sql+" and org_detailpost in (";
for(int i=0;i<postIDlength;i++)
{
sql=sql+postID[i];
if(i!=(postIDlength-1))
sql=sql+",";
}
sql=sql+")";
}
if (degreeCode!=0)
{
sql=sql+" and org_detaildegree="+degreeCode+"";
}
if (politicalPosition!=0)
{
sql=sql+" and org_detailpoliticalPosition="+politicalPosition+"";
}
if (technicalPosition!=0)
{
sql=sql+" and org_detailtechnicalPosition="+technicalPosition+"";
}
if (technicalPosition!=0)
{
sql=sql+" and org_detailpoliticalLevel="+politicalLevel+"";
}
if (grade!=0)
{
sql=sql+" and org_detailgrade="+grade+"";
}
if (longevity!=0)
{
sql=sql+" and org_detaillongevity="+longevity+"";
}
if(getAllowance!=null)
{
if (allowance==0||allowance==1)
{
sql=sql+" and org_detailallowance="+allowance+"";
}
}
}
User[] userList =null;
userList=urcomplexSearch(sql);
logaddLog(1,1,1,uid,userIP,uid+"于("+today+")查询员工");int cnt=userListlength;//总记录数
int pageSize=10;//每页显示记录数
int curPage=1;//当前页
int cntPage;//总页数
int m=1; if (cnt>0)
{
if (cnt%pageSize==0)
cntPage=cnt/pageSize;
else
cntPage=cnt/pageSize+1;
}
else
cntPage=0; if (getPage==null)
{
getPage="1";
curPage=1;
}
else
curPage=IntegerparseInt(getPagetrim());
%><form name="thisform" action="userSearchDeljsp" method="post">
<table bgColor="#FFFFFF" border="1" borderColorDark="#ffffff" borderColorLight="#c0c0c0" cellSpacing="0" width="95%" cellpadding="4">
<tr height="25" align="center" bgcolor="#959595">
<td></td>
<td><font color="#FFFFFF">姓名</font></td>
<td><font color="#FFFFFF">性别</font></td>
<td> <font color="#FFFFFF">所在部门</font></td>
<td> <font color="#FFFFFF">办公地址</font></td>
<td><font color="#FFFFFF">联系电话</font></td>
</tr>
<%
int u=1;
for(int i=0;i<cnt;i++)
{
//显示记录的起始位置
int j=(curPage-1)pageSize;
//显示记录的末位置
int k=curPagepageSize;
//只显示page_size条数据
if(m>j&&m<=k)
{
String userId=userList[i]getUserID();
String gender=userList[i]getGender();
String name=userList[i]getName();
String tel=userList[i]getTel();
String useAddress=userList[i]getAddress();
long dep_id=userList[i]getDepID();
String dname=depgetName(userList[i]getDepID());
if(tel==null||telequals("null"))
tel="";
if(useAddress==null||useAddressequals("null"))
useAddress="";
//判断没一行该输出的颜色
if((u%2)==0)
{
outprintln("<tr bgcolor=#D7D7D7 onMouseOver=thisstylebackgroundColor='#fcd4d7'; onMouseOut=if(selectedItem!=thisid){thisstylebackgroundColor='#D7D7D7';}>");
}
else
{
outprintln("<tr onMouseOver=thisstylebackgroundColor='#fcd4d7'; onMouseOut=if(selectedItem!=thisid){thisstylebackgroundColor='#FFFFFF';}>");
}
u++;
%>
<td align=center><input type="checkbox" name="checkbox" id="CHK_+<%=userId%>" value="<%=userId%>"></td>
<td align=center>
<%
long departmentID=urgetDepID(uid);
if(uphaveRight(uid,"USER_COMPLEXQUERY")==true)
{
%>
<a href="userAnalyzejspuserId=<%=userId%>&dep_id=<%=dep_id%>&toPage=<%=curPage%>"><font color="#330099">
<%
}
else if(uphaveRight(uid,"DEPARTMENT_PLATFORM")==true&&dep_id==departmentID)
{
%>
<a href="userAnalyzejspuserId=<%=userId%>&dep_id=<%=dep_id%>&toPage=<%=curPage%>"><font color="#330099">
<%
}
%>
<%=name%></font></a></td>
<%
if(gendertrim()equals("0"))
outprintln("<td align=center>男</td>");
else
outprintln("<td align=center>女</td>");
%>
<td align=center><a href="depintrojspid=<%=dep_id%>&toPage=<%=curPage%>"><font color="#330099"><%=dname%></font></a></td>
<td align=center> <%=useAddress%></td>
<td align=center> <%=tel%></td>
</tr>
<%
}//end if m++;
}//end for
%>
<input type=hidden name="sql" value="<%=sql%>">
<input type=hidden name="page" value="<%=curPage%>">
</table>
</form>
<form name=pageform action="searchActionjsp" method="post">
<table border="0" width="95%">
<tr>
<td align="center">第<%=curPage%>页/共<%=cntPage%>页</td>
<td align="left">
<img name="firstpage" src="/Image/btn_firstpagegif" style="cursor:hand" onclick="pageClick(1)" <%=curPage>1" ":"disabled"%>>
<img name="prepage" src="/Image/btn_prepagegif" style="cursor:hand" onclick="pageClick(<%=curPage-1%>)" <%=curPage>1" ":"disabled"%>>
<img name="nextpage" src="/Image/btn_nextpagegif" style="cursor:hand" onclick="pageClick(<%=curPage+1%>)" <%=curPage<cntPage" ":"disabled"%>>
<img name="lastpage" src="/Image/btn_lastpagegif" style="cursor:hand" onclick="pageClick(<%=cntPage%>)" <%=curPage<cntPage" ":"disabled"%>>
</td>
<td align=left width=55%>
到第<input type="text" name="goPage" size="4">页
<img border="0" src="/Image/icon_searchgif" style="cursor:hand" onclick="aPage()">
</td>
</tr><tr>
<td colspan="3" valign="middle" width="23%" align="right">
<%
if(uphaveRight(uid,"USER_MANAGE")==true)
{
%>
<img border="0" src="/Image/btn_deletegif" style="cursor:hand" onclick="delUser()">
<%}%>
<img border="0" src="/Image/btn_returngif" style="cursor:hand" onclick="back()">
</td>
<input type=hidden name="sql" value="<%=sql%>">
<input type=hidden name="toPage">
</td>
</tr>
</table>
</form>
<br>
<br>
</td>
</tr>
</table>
</td>
</tr>
</table>
<%
}//end else
}//end try
catch(Exception e)
{
outprintln(egetMessage());
}
%>
</td>
</tr>
</table>
1:新建一个数据库
create database 数据库名
2:新建一个表
create table 表名
(
字段名 类型 是否为空
)
3:删除一个表
drop table 表名
4:增加一个记录
insert 表名 [(字段)] values ( 内容 )
5:删除一个记录
delete [from] 表名 where 条件
6、修改一个记录
update 表名 set 字段名=更新内容 where 条件
7、在原表中增加一个字段
alter table 表名 add column 字段名 类型
8:在原表中删除一个字段
alter table 表名 drop column 字段名
9、查询一个表记录
select from 表名
10、带条件查询一个表记录
select from 表名 where =条件
Anllen,这样做是不科学的,如果是定时发送你可以考虑使用sql server中的计划,他可以定义执行某些任务,同时在sql server 2005以后还加入机器空闲时执行等等,而且还是可在失败时重试(重试次数自己设置),还可以对部分成功时进行记录等等。
如果是要求立即执行或是其他不能指执行条件时,可以考虑sql server 2005之后的server broker,这种机制较为安全。同时因为使用queue的原因,使消息只到达一次而不会重复,解决实际工作中的数据库与程序间的异步传输问题。
既然有这么多好的方案为什么还考虑重复地循环地查询数据库呢——你的数据库效率被拉的很慢的,别忘记了还是许多锁机制,会导致SQL server不再及时响应外部请求的!
别着急,很简单,看下面:
private DataTable GetTable(){
string connstring = "server=127001\\SQLEXPRESS;database=数据库名;uid=用户名;pwd=密码";//连接串,连接你的数据库
SqlConnection conn = new SqlConnection(connstring);
string sql = "select from Users";//查询SQL,根据你的表来写
SqlCommand cmd = new SqlCommand(sql, conn);
connOpen();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sdaFill(dt);//执行查询并加载数据到DataTable中
connClose();
cmdDispose();
return dt;
}
然后,dataGridView1DataSourse=dt;
就可以在窗体中显示数据了。
模糊查询的话,方法和这个一样,只是把SQL改一下,where条件中加上 like 即可。
如果要求代码的完美,需要在数据层写一个单独的获取表的方法,即:
/// <summary>/// 将数据库表读取到内存DataTable中
/// </summary>
/// <param name="sql">传入的sql字符串</param>
/// <returns>内存DataTable表</returns>
public static DataTable GetDataTable(string sql)
{
string connstring = "server=127001\\SQLEXPRESS;database=数据库名;uid=用户名;pwd=密码";//连接串,连接你的数据库
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand(sql, conn);
connOpen();
SqlCommand cmd = Cmd(sql);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sdaFill(dt);
connClose();
cmdDispose();
return dt;
}
然后在业务层写一个调用的方法,传入SQL,即:
public static DataTable GetDataTableBLL(){
string sql="select from table";
DataTable dt = new DataTable();
dt = GetDataTable(sql);
return dt;
}
需要的数据不同,传入的SQL不同。
以上就是关于怎么用jdbc连接sqlserver数据库查询数据全部的内容,包括:怎么用jdbc连接sqlserver数据库查询数据、asp查asp数据库时,联合查询代码、jsp查询数据库代码等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)