‘壹’ 如何把java对象存入数据库
假设有这么个对象:
import java.io.Serializable;
public class MyObject implements Serializable {
private static final long serialVersionUID = 1L;
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
//测试 的方法如下
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class test {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
MyObject obj = new MyObject();
obj.setI(4567);
write(Object2Bytes(obj));
// read();
}
public static void write(byte[] b) throws ClassNotFoundException {
System.out.println(b.length);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
try {
Connection con = DriverManager.getConnection("jdbc:odbc:temp");
String sql = "insert into tab values(?)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setBytes(1, b);
pstmt.execute();
pstmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void read() throws ClassNotFoundException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
try {
Connection con = DriverManager.getConnection("jdbc:odbc:temp");
String sql = "select * from tab";
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet res = pstmt.executeQuery();
while (res != null && res.next()) {
byte[] b = res.getBytes("key");
System.out.println(b.length);
MyObject obj = (MyObject) Bytes2Object(b);
System.out.println(obj.getI());
}
pstmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 将对象转换成字节数组
public static byte[] Object2Bytes(Object obj) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
return baos.toByteArray();
}
// 将字节数组转换成为对象
public static Object Bytes2Object(byte[] b) throws IOException,
ClassNotFoundException {
ByteArrayInputStream s = new ByteArrayInputStream(b);
ObjectInputStream ois = new ObjectInputStream(s);
Object obj = ois.readObject();
return obj;
}
}
‘贰’ 在java中如何将数组里的数据存入数据库呢
保存字节数组到数据库分两步:
第一、利用FileInputStream.read(byte[])方法把内容读取到byte[]数组中,比如图片是由二进制数组成的,就可以定义为一个字节数组。
第二、在数据库中对应记录字段应该设置为blob类型,这样就能够顺利保存了
事例代码如下:
PreparedStatement stmt = connection.generatePreparedStatement("INSERT INTO ... ");
stmt.setBytes(1, yourByteArray);
其中,yourByteArray是你读出来的字符数组。
‘叁’ 如何将对象持久化到数据库中BLOB
对象持久化,也就是可以把这个对象永远的保存起来,这里的保存不仅是对象本身,还包括他的属性和所依赖的其他类。通常,对象可以持久化到文件或者是数据库中。我这里只介绍如何将对象存储到数据库中。恰巧Oracle数据库为我们提供了这样的方便。
在Oracle中,有一种blog的字段类型,它是用来存储大量的二进制数据的。我们就利用这个字段去存储对象信息。
首先建立一个测试表:
create table TESTBLOB
(
NAME VARCHAR2(50) not null,
CONTENT BLOB not null,
ID NUMBER(8) not null
)alter table TESTBLOB
add constraint IDFORTEST primary key (ID);
只用三个字段,其中id是属性,content是我们要存储对象的字段。
先来看看我们要存入的对象:
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class TestObject implements Serializable {
private static final long serialVersionUID = 4558876142427402513L;
/**
* @param args
*/
private String name;
private String password;
private Date date;
private List<City> cityList;
public List<City> getCityList() {
return cityList;
}
public void setCityList(List<City> cityList) {
this.cityList = cityList;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
记得要实现Serializable接口,可以看到这是一个包含了string,date,和list类型的对象,为了给测试增加复杂度,我们的list是另外一个对象(city)的list,如下:
import java.io.Serializable;
public class City implements Serializable{
private static final long serialVersionUID = 4558876127402513L;
private String name;
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
City对象包括了城市名称和区号。下面是主要的应用了。
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import oracle.sql.BLOB;
public class Test {
public static void main(String[] args) {
//创建测试用对象
City beijing = new City();
beijing.setName("北京");
beijing.setCode("010");
City shanghai = new City();
shanghai.setName("上海");
shanghai.setCode("020");
City tianjin = new City();
tianjin.setName("天津");
tianjin.setCode("021");
List<City> cityList = new ArrayList<City>();
cityList.add(beijing);
cityList.add(shanghai);
cityList.add(tianjin);
TestObject obj = new TestObject();
obj.setName("yangsq");
obj.setPassword("111");
obj.setDate(new Date());
obj.setCityList(cityList);
try{
//将对象存入blob字段
ByteArrayOutputStream byteOut=new ByteArrayOutputStream();
ObjectOutputStream outObj=new ObjectOutputStream(byteOut);
outObj.writeObject(obj) ;
final byte[] objbytes=byteOut.toByteArray();
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@***.***.***.***:1521:****", "yangsq", "yangsq");
con.setAutoCommit(false);
Statement st = con.createStatement();
st.executeUpdate("insert into TESTBLOB (ID, NAME, CONTENT) values (1, 'test1', empty_blob())");
ResultSet rs = st.executeQuery("select CONTENT from TESTBLOB where ID=1 for update");
if (rs.next()) {
BLOB blob = (BLOB) rs.getBlob("CONTENT");
OutputStream outStream = blob.getBinaryOutputStream();
outStream.write(objbytes, 0, objbytes.length);
outStream.flush();
outStream.close();
}
byteOut.close();
outObj.close();
con.commit();
//取出blob字段中的对象,并恢复
rs = st.executeQuery("select CONTENT from TESTBLOB where ID=1");
BLOB inblob = null;
if (rs.next()) {
inblob = (BLOB) rs.getBlob("CONTENT");
}
InputStream is = inblob.getBinaryStream();
BufferedInputStream input = new BufferedInputStream(is);
byte[] buff = new byte[inblob.getBufferSize()];
while(-1 != (input.read(buff, 0, buff.length)));
ObjectInputStream in =
new ObjectInputStream(
new ByteArrayInputStream(
buff));
TestObject w3 = (TestObject)in.readObject();
System.out.println(w3.getName());
System.out.println(w3.getPassword());
System.out.println(w3.getDate());
List<City> list = w3.getCityList();
for(City city : list){
System.out.println(city.getName() + " " + city.getCode());
}
st.close();
con.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
}
代码的蓝色部分创建了要存储的对象。再看红色的对象写入部分,它首先把对象转化成二进制流的形式。对于blob字段,我们不能简单的在insert时插入,实际上,insert时,对于blob字段,只能先插入一个空的blob对象empty_blob(),然后再进行"select CONTENT from TESTBLOB where ID=1 for update"对blob字段进行更新。返回后,我们只要把对象的二进制流写入即可。
OutputStream outStream = blob.getBinaryOutputStream();
outStream.write(objbytes, 0, objbytes.length);
需要注意的是,上述步骤必须设置con.setAutoCommit(false),否则oracle会抛出异常。
接下来,绿色的代码是读取数据库中blob字段的对象,并恢复。我们要知道的是,所有对blob字段的操作都是二进制的,即插入时是二进制流,读出时也是二进制流。然后用io修饰器(ObjectInputStream)去修饰。以前学习java时,感觉它的io好繁琐啊,现在感觉还真是各有其用。下面是测试的输出结果。
yangsq
111
Tue Mar 27 12:11:28 CST 2007
北京 010
上海 020
天津 021
需要说明一下,buff的size一定要足够大,否则将抛出异常。在这里,我使用的是inblob.getBufferSize()来设置buff的size,这并不是一种好的方法,因为一般inblob.getBufferSize()都是32768,很可能出现异常,所以这个size最好自己设置,或系统运行时刻设置(幸好java提供数组长度的运行时刻设置)。
‘肆’ 如何将一个数组存入数据库中
将一个数组存入数据库和使用的语言有关系。
通常的做法是将数组的内容转换后传递到和语言相关的数据处理方法中进行处理。
涉及到的数据转换的方法:
1:可以转换为json格式
[{key:1},{key:2}]
2:可以转换为xml
<values>
<key>1</key><key>2</key>
</values>
数据处理方法解析转换后的字符串,执行数据库保存操作。
‘伍’ 如何把数组存进数据库
存可以把数组连成字符串的形式存
取得时候再分割就好了
比如5个数字
update
表
set
unum="1,2,3,4,5"
取出来以后用split()函数分割
就好了
‘陆’ 在JSP页面用json保存了一个对象数组,怎么把这个对象数组传到后台保存到数据库中
ajax提交后台方法名geteway,你的json数组就是postData,后台接收一下保存到数据库,大概是这个流程
‘柒’ 如何:将数据从对象保存到数据库
有关更多信息,请参见 TableAdapter 概述。若要保存对象集合中的数据,请循环通过对象集合(例如,for-next 循环),然后使用 TableAdapter 的 DBDirect 方法之一将每个对象的值发送到数据库中。默认情况下,DBDirect 方法在 TableAdapter 上创建,能够直接对数据库执行操作。这些方法可以直接调用,它们不要求 DataSet 或DataTable 对象来协调更改即可将更新发送到数据库。注意配置TableAdapter 时,主查询必须提供足够的信息,才能创建 DBDirect 方法。例如,如果将 TableAdapter 配置为从未定义主键列的表中查询数据,它将不会生成 DBDirect 方法。 TableAdapter DBDirect 方法 说明TableAdapter.Insert向数据库中添加新记录,此方法允许将值作为方法参数传入各个列。TableAdapter.Update更新数据库中的现有记录。Update 方法将原始列值和新列值用作方法参数。原始值用于定位原始记录,新值用于更新该记录。通过将 DataSet、DataTable、DataRow、或 DataRow 数组用作方法参数,TableAdapter.Update 方法还可用于将数据集中的更改协调回数据库。TableAdapter.Delete在基于作为方法参数传入的原始列值的数据库中,删除其现有记录。将对象中的新记录保存到数据库中通过将值传递给 TableAdapter.Insert 方法可创建这些记录。下面的示例通过将 currentCustomer 对象中的值传递给 TableAdapter.Insert 方法,在 Customers 表中创建一项新的客户记录。 Visual Basic PrivateSub AddNewCustomer(ByVal currentCustomer As Customer) CustomersTableAdapter.Insert( _ currentCustomer.CustomerID, _ currentCustomer.CompanyName, _ currentCustomer.ContactName, _ currentCustomer.ContactTitle, _ currentCustomer.Address, _ currentCustomer.City, _ currentCustomer.Region, _ currentCustomer.PostalCode, _ currentCustomer.Country, _ currentCustomer.Phone, _ currentCustomer.Fax) EndSub C# privatevoid AddNewCustomers(Customer currentCustomer) { customersTableAdapter.Insert( currentCustomer.CustomerID, currentCustomer.CompanyName, currentCustomer.ContactName, currentCustomer.ContactTitle, currentCustomer.Address, currentCustomer.City, currentCustomer.Region, currentCustomer.PostalCode, currentCustomer.Country, currentCustomer.Phone, currentCustomer.Fax); } J# privatevoid AddNewCustomers(Customer currentCustomer) { .Insert( currentCustomer.get_CustomerID(), currentCustomer.get_CompanyName(), currentCustomer.get_ContactName(), currentCustomer.get_ContactTitle(), currentCustomer.get_Address(), currentCustomer.get_City(), currentCustomer.get_Region(), currentCustomer.get_PostalCode(), currentCustomer.get_Country(), currentCustomer.get_Phone(), currentCustomer.get_Fax()); }将对象中的现有记录更新到数据库修改记录:调用 TableAdapter.Update 方法并传入新值可更新记录,而传入原始值可定位记录。注意对象需要保留其原始值,才能将它们传递给 Update 方法。此示例使用前缀为 orig 的属性存储原始值。下面的示例通过将 Customer 对象中的新值和原始值传递给 TableAdapter.Update 方法,更新 Customers 表中的现有记录。 Visual Basic PrivateSub UpdateCustomer(ByVal cust As Customer) CustomersTableAdapter.Update( _ cust.CustomerID, _ cust.CompanyName, _ cust.ContactName, _ cust.ContactTitle, _ cust.Address, _ cust.City, _ cust.Region, _ cust.PostalCode, _ cust.Country, _ cust.Phone, _ cust.Fax, _ cust.origCustomerID, _ cust.origCompanyName, _ cust.origContactName, _ cust.origContactTitle, _ cust.origAddress, _ cust.origCity, _ cust.origRegion, _ cust.origPostalCode, _ cust.origCountry, _ cust.origPhone, _ cust.origFax) EndSub C# privatevoid UpdateCustomer(Customer cust) { customersTableAdapter.Update( cust.CustomerID, cust.CompanyName, cust.ContactName, cust.ContactTitle, cust.Address, cust.City, cust.Region, cust.PostalCode, cust.Country, cust.Phone, cust.Fax, cust.origCustomerID, cust.origCompanyName, cust.origContactName, cust.origContactTitle, cust.origAddress, cust.origCity, cust.origRegion, cust.origPostalCode, cust.origCountry, cust.origPhone, cust.origFax); } J# privatevoid UpdateCustomer(Customer cust) { .Update( cust.get_CustomerID(), cust.get_CompanyName(), cust.get_ContactName(), cust.get_ContactTitle(), cust.get_Address(), cust.get_City(), cust.get_Region(), cust.get_PostalCode(), cust.get_Country(), cust.get_Phone(), cust.get_Fax(), cust.get_origCustomerID(), cust.get_origCompanyName(), cust.get_origContactName(), cust.get_origContactTitle(), cust.get_origAddress(), cust.get_origCity(), cust.get_origRegion(), cust.get_origPostalCode(), cust.get_origCountry(), cust.get_origPhone(), cust.get_origFax()); }删除数据库中的现有记录通过调用 TableAdapter.Delete 方法并传入原始值定位记录,可删除记录。注意对象需要保留其原始值,才能将它们传递给 Delete 方法。 Visual Basic PrivateSub DeleteCustomer(ByVal cust As Customer) CustomersTableAdapter.Delete( _ cust.origCustomerID, _ cust.origCompanyName, _ cust.origContactName, _ cust.origContactTitle, _ cust.origAddress, _ cust.origCity, _ cust.origRegion, _ cust.origPostalCode, _ cust.origCountry, _ cust.origPhone, _ cust.origFax) EndSub C# privatevoid DeleteCustomer(Customer cust) { customersTableAdapter.Delete( cust.origCustomerID, cust.origCompanyName, cust.origContactName, cust.origContactTitle, cust.origAddress, cust.origCity, cust.origRegion, cust.origPostalCode, cust.origCountry, cust.origPhone, cust.origFax); } J# privatevoid DeleteCustomer(Customer cust) { .Delete( cust.get_origCustomerID(), cust.get_origCompanyName(), cust.get_origContactName(), cust.get_origContactTitle(), cust.get_origAddress(), cust.get_origCity(), cust.get_origRegion(), cust.get_origPostalCode(), cust.get_origCountry(), cust.get_origPhone(), cust.get_origFax()); }安全您必须具有相应的权限,才能对数据库中的表执行选定的 INSERT、UPDATE 或 DELETE。
‘捌’ C#写上位机怎么把数组存到数据库相应字段
一)Access数据库
1) 设计表,将段M1,M2,M3的类型设置为"OLE对象"
//要写入数据库的数据
byte[]m1=……;
byte[]m2=……;
byte[]m3=……;
//数据库
SqlConnectionconn=newSqlConnection("你的连接串");
conn.Open()
SqlCommandcmd=newSqlCommand();
cmd.Connection=conn;
cmd.CommandText="INSERTINTO[m]([m1],[m2],[m3])VALUES(@m1,@m2,@m3)";
//添加参数
SqlParameterp=cmd.Parameters.Add("m1",SqlDbType.VarBinary);
p.Value=m1;
p=cmd.Parameters.Add("m2",SqlDbType.VarBinary);
p.Value=m2;
p=cmd.Parameters.Add("m3",SqlDbType.VarBinary);
p.Value=m3;
//执行
cmd.ExecuteNonQuery();
‘玖’ 如何把java对象存入数据库
原生java对象存数据库,可以考虑将对象转成字节数组,写入数据库;
一般常用做法是一个属性对应一个字段,不会直接写入java 对象