初级DBConnection

本文介绍了一个Java类ConnDB,用于实现与SQL Server数据库的连接,并提供了执行查询和更新操作的方法。此外,还展示了LzwUploadBean类,用于处理文件上传到数据库及本地文件系统的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

connDB.java package com.core; import java.sql.*; public class ConnDB{                 Connection conn=null;                 Statement stmt=null;                 ResultSet rs=null;         public ConnDB(){                 try{                         Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");                 }catch(java.lang.ClassNotFoundException e){                         System.err.println("连接时出错:"+e.getMessage());                 }         }         public ResultSet executeQuery(String sql){                 try{                         conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_database03;user=sa;password=911");                         stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);                         rs=stmt.executeQuery(sql);                 }catch(SQLException ex){                         System.err.println("查询时的错误信息:"+ex.getMessage());                         }finally{}                 return rs;         }  public int executeUpdate(String sql){                 int result=0;                 try{                         conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_database03;user=sa;password=911");                         stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);                         result=stmt.executeUpdate(sql);                 }catch(SQLException ex){                         result=0;                         }finally{}                 return result;         }        public void close(){          try {            if (rs != null) rs.close();          }          catch (Exception e) {            e.printStackTrace(System.err);          }finally{}          try {            if (stmt != null) stmt.close();          }          catch (Exception e) {            e.printStackTrace(System.err);          }finally{}          try {            if (conn != null) {              conn.close();            }          }          catch (Exception e) {            e.printStackTrace(System.err);          }finally{}        } }

<tr> <td height="20" align="center"> <a href="#" onClick="window.open('goods_detail.jsp?ID=<%=ID%>','','width=587,height=230')"> <%=goodsName%></a></td>       <td align="left"><%=introduce%></td>       <td align="center"><%=newgoods%></td>       <td align="center"><%=sale%></td>       <td align="center"><a href="goods_modify.jsp?ID=<%=ID%>"><img src="images/modify.gif" width="15" height="15" border="0"></a></td>         <td align="center"><a href="goods_del.jsp?ID=<%=ID%>"><img src="images/del.gif" width="16" height="16" border="0"></a></td> </tr>

数据库中 Picture :hwdlz.jpg 取     <img src="images/goods/<%=Picture%>">

<a href="#" onClick="opendialog()">购买须知</a> <script language="javascript">  function opendialog(){  var width=screen.width;  var height=screen.height;  window.showModalDialog("notice.jsp","","dialogWidth="+width+"px;dialogHeight="+height+"px;status=no;help=no;scrollbars=no")  } </script>

只显示三条的方法 for (int i=0 ;i<3 ;i++){    Rs.next(); } 全部显示 While(Rs.next()){}

Integer转String是,Integer.toString();

语法错误,仅当源级别为5。0时已参数化的类型才可用 eclipse里面的jdk设置有问题,查看下是不是5.0的     首选项/java/编译器/jdk一致性   5.0 JDK 1.5 以上的 Integer 和 int 可以混用,JDK 1.5 以下的采用:

int --> Integer int k = 5; Integer num = new Integer(k);

Integer --> int Integer num = new Integer(5); int k = num.intValue();

int --> String int k = 5; String str = k + ""; 或:String str = String.valueOf(k);

LzwUploadBean.java import java.io.*; import java.sql.*; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.servlet.jsp.PageContext; public class LzwUploadBean {  private InputStream InputStreamState;  private String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";  private String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_database11"; private String user = "sa";  private String password = "911";  private Connection conn;  private PageContext pageContext;  private long fileSize;  private String errorMessage = "";  private Map<String, String> lzwParameter = new HashMap<String, String>();  public LzwUploadBean() { }  public LzwUploadBean(String driver, String url) {   super();   this.driver = driver;   this.url = url;  }  private void resolverForm() {    }

 public boolean uploadToDB(String driver, String url, String tabName,    String... valuesArg) {     }  public void printOutputStreamFromDB(String tabName, String condition,    String column, OutputStream outputStream) {   Statement st = null;   ResultSet rs = null;   try {    Class.forName(driver);    conn = DriverManager.getConnection(url, user, password);    st = conn.createStatement();    rs = st.executeQuery("select " + column + " from " + tabName      + " where " + condition);    while (rs.next()) {     outputStream.write(rs.getBytes(1));    }    outputStream.close();    rs.close();    st.close();    conn.close();   } catch (UnsupportedEncodingException e) {    e.printStackTrace();   } catch (ClassNotFoundException e) {    e.printStackTrace();   } catch (SQLException e) {    e.printStackTrace();   } catch (IOException e) {    e.printStackTrace();   }  }  public boolean uploadToFile(String filearg, String filename, String filePath) {   if (filename == null || filename.equals("")) {    filename = System.currentTimeMillis()      + new File(getParameter(filearg + "_filename")).getName();   }   String contentType = pageContext.getRequest().getContentType();   if (!isMultipar(contentType))    return false;   resolverForm();   if (filePath.charAt(filePath.length() - 1) != File.separatorChar)    filePath += File.separatorChar;   String submit = getParameter("Submit");   String file = getParameter(filearg);   if (submit != null && file != null) {    try {     File newfile = new File(new String((filePath + new File(       filename).getName()).getBytes("iso-8859-1")));     newfile.createNewFile();     FileOutputStream fout = new FileOutputStream(newfile);     fout.write(file.getBytes("iso-8859-1"));     fout.close();    } catch (UnsupportedEncodingException e) {     e.printStackTrace();    } catch (FileNotFoundException e) {     e.printStackTrace();    } catch (IOException e) {     e.printStackTrace();    }    return true;   }   return false;  }  public Set<String> getParameterNames() {   resolverForm();   return lzwParameter.keySet();  }  public void setPassword(String password) {   this.password = password;  }  public void setUser(String user) {   this.user = user;  }  private boolean isMultipar(String contentType) {   try {    if (contentType != null      && !contentType.startsWith("multipart/form-data")) {     throw new Exception(       "请设置Form表单的enctype属性为:/"multipart/form-data/"");    } else {     return true;    }   } catch (Exception e) {    e.printStackTrace();   }   return false;  }  public void setPageContext(PageContext pageContext) {   this.pageContext = pageContext;  }  public void setFileSize(long fileSize) {   this.fileSize = fileSize;  } } <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <jsp:useBean id="lzwUpload" class="lzwBean.LzwUploadBean" scope="page"/>

Index.jsp <% lzwUpload.setPageContext(pageContext); String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver"; String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_database11;user=sa;password=911"; if(lzwUpload.getParameter("Submit")!=null){ if(lzwUpload.getParameter("file")!=null&&lzwUpload.getParameter("file").equals("")){ out.println("<script >alert('请选择文件');</script>"); }else{ lzwUpload.uploadToDB(driver,url,"tab_oneFormUploadFile",lzwUpload.getParameter("file")); out.println("<script >alert('上传完毕');</script>"); } } %> 请选择上传的文件: <input name="file" type="file" size="35"> 注:只能上传GIF、JPG、BMP格式图片。 <input name="Submit" type="submit" value="提交">    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值