日期:2014-05-18 浏览次数:20871 次
mport java.sql.*; public class TestInsert { public static void main(String[] args){ String connectionUrl = "jdbc:sqlserver://localhost:1433;DatabaseName=mydata;user=sa;password="; Connection conn = null; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); conn = DriverManager.getConnection(connectionUrl); java.io.File file = new java.io.File("d:\\123.jpg"); java.io.FileInputStream fis = new java.io.FileInputStream(file); ResultSet result=null; String sql=null; PreparedStatement prestmt=null; sql="insert into test(tid,tdata) values(?,?)"; prestmt =conn.prepareStatement(sql); prestmt.setInt(1, 1); prestmt.setBinaryStream(2,fis,(int)file.length()); prestmt.executeUpdate(); System.out.println("success!"); conn.close(); } catch(Exception e){System.out.println("error: " + e);} } }
------解决方案--------------------
存放到硬盘上:
jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'daoRuform.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="uploadDRFile.jsp" method="post" enctype="multipart/form-data"> <input name ="daoru" type="file"> <input name = "tijiao" type="submit" value="导入"> </form> </body> </html>
------解决方案--------------------
java代码,写在jsp里的
<%@ page contentType="text/html; charset=gb2312" %> <%@ page language="java" %> <%@ page import="java.sql.*" %> <%@ page import="java.io.*"%> <%@ page import="java.util.*"%> <html> <head> <title> 导入测试 </title> </head> <body bgcolor="#ffffff"> <center> <% int MAX_SIZE = 102400 * 102400;//定义上载文件的最大字节 String rootPath; // 创建根路径的保存变量 DataInputStream in = null; //声明文件读入类 Fi