導航:首頁 > 數據處理 > 如何把對象數組存到資料庫

如何把對象數組存到資料庫

發布時間:2022-11-14 02:50:46

『壹』 如何把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 對象

閱讀全文

與如何把對象數組存到資料庫相關的資料

熱點內容
剛體轉動數據保留多少位 瀏覽:40
微信上的配樂朗誦小程序叫什麼 瀏覽:837
國際貨運代理的經營范圍包括哪些 瀏覽:570
收銀機的程序在哪裡 瀏覽:982
太原綜合市場是什麼意思 瀏覽:226
瀏覽器移動數據很慢為什麼 瀏覽:526
資料庫欄位對應的實體類怎麼寫 瀏覽:96
連鎖市場規劃如何列名單 瀏覽:403
為什麼給客戶配置存款產品 瀏覽:693
工業信息局是什麼編制 瀏覽:137
小漁市場怎麼樣 瀏覽:871
如何用婉轉的話說老公不回信息 瀏覽:963
淘寶萬寶路怎麼交易 瀏覽:624
華中數控程序如何校驗 瀏覽:847
怎麼樣介紹產品和文字 瀏覽:362
臨沂代理記賬多少一年 瀏覽:416
撫州抖音小程序開發一般多少錢 瀏覽:518
正規人事代理有哪些 瀏覽:384
貓達人微信小程序是什麼 瀏覽:508
華為的接入技術主要有哪些 瀏覽:323