Java数据库处理的方法库DBUtil

更新时间:2023-06-02 06:51:01 阅读量: 实用文档 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

Java数据库处理的方法库DBUtil

2010年07月16日 13:28 | 分类:测试开发蒋 刚毅

1.postgres数据库的select操作,返回select后返回的第一行数据,返回类型为string,若要返回int,只需将getString改为getInt

public static String PgDBSelect(String sql) throws

ClassNotFoundException, SQLException{

String dbURL=”jdbc:postgresql://172.16.4.25:5432/skyups”; String dbuser=”***”;

String dbpasswd=”***”;

Class.forName(”org.postgresql.Driver”);

Connection conn = DriverManager.getConnection(dbURL,dbuser,dbpasswd); Statement stmt =

conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_READ_ONLY);

ResultSet rs = stmt.executeQuery(sql);

rs.next();

String value=rs.getString(1);

rs.close();

stmt.close();

conn.close();

return value;

}

2.postgres数据的执行操作,可执行instert、delete、update等操作,不返回数据

public static void PgDBUpdate(String sql) throws ClassNotFoundException, SQLException{

String dbURL=”jdbc:postgresql://172.16.4.25:5432/skyups”; String dbuser=”***”;

String dbpasswd=”***”;

Class.forName(”org.postgresql.Driver”);

Connection conn = DriverManager.getConnection(dbURL,dbuser,dbpasswd); Statement stmt =

conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

stmt.executeUpdate(sql);

stmt.close();

conn.close();

}

3. oracle数据库的select操作,返回select后返回的第一行数据,若要返回int,只需将getString改为getInt

public static String OracleDBSelect(String sql) throws

ClassNotFoundException, SQLException{

String dbURL=”jdbc:oracle:thin:@172.16.4.21:1521:skytest”; String dbuser=”***”;

String dbpasswd=”***”;

Class.forName(”oracle.jdbc.OracleDriver”);

Connection conn = DriverManager.getConnection(dbURL,dbuser,dbpasswd); Statement stmt =

conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_READ_ONLY);

ResultSet rs = stmt.executeQuery(sql);

rs.next();

int expbalance=rs.getString(1);

rs.close();

stmt.close();

conn.close();

return expbalance;

}

4.oralce数据的执行操作,可执行instert、delete、update等操作,不返回数据

public static void OracleDBUpdate(String sql) throws

ClassNotFoundException, SQLException{

String dbURL=”jdbc:oracle:thin:@172.16.4.21:1521:skytest”; String dbuser=”***”;

String dbpasswd=”***”;

Class.forName(”oracle.jdbc.OracleDriver”);

Connection conn = DriverManager.getConnection(dbURL,dbuser,dbpasswd); Statement stmt =

conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

stmt.executeUpdate(sql);

stmt.close();

conn.close();

}

5.Cassandra非关系型数据库的操作,包括delete、insert、read等。 public static void CassandraRemove(String USkyid)throws

IllegalStateException, PoolExhaustedException,Exception {

CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get(); CassandraClient client = pool.borrowClient(”172.16.4.244″, 9160); try{

Keyspace keyspace = client.getKeyspace(”skyups”);

ColumnPath columnPath = new ColumnPath();

columnPath.setColumn_family(”UserInfo”);

//delete

keyspace.remove(USkyid, columnPath);

/*

// read

Column col = keyspace.getColumn(value, columnPath);

System.out.println(”Read from cassandra: ” +

string(col.getValue()));

// insert

keyspace.insert(”key”, columnPath, bytes(”value”)); */

} finally{

pool.releaseClient(client);

}

}

利用方法库执行一次完整的junit测试举例:

step1.设置一条用户信息,包括所有字段参数。step2:再发送一条设置信息,其中用户的出生日期为空。step3:删除这条用户信息,恢复环境。

@Before

public void setUp() throws Exception {

Socket socket=new Socket(ServerIP,Port);

DataOutputStream dos=new DataOutputStream(socket.getOutputStream()); DataInputStream dis=new DataInputStream(socket.getInputStream()); byte[] resp=new byte[1024];

System.out.println(”StartUp:预置测试环境,初始化设置1条用户信息“); byte[] setuserinfomsg1=PackMsg.SetUserInfoMsg(USkyid, UUserName,

UNickname, URealName, USex, UBirthday, UAnimals, UStar, UBlood, UMarried, UPortraitId, UDefinePortrait, UCountry, UProvince, UCity, UHometown, ULongitude, ULatitude, USignature, UDesc, UEmail, UEmailChecked, UMobile, UMobileChecked, UTelephone, UVocation, USchoolGraduated, UPrivacy, UIdCardNo,HasPic);

dos.write(setuserinfomsg1);dis.read(resp);

Thread.sleep(1000);

dos.flush();dis.close();socket.close();

}

@Test

public void testSetUserInfo_Edit_BirthDay() throws Exception { Socket socket=new Socket(ServerIP,Port);

DataOutputStream dos=new DataOutputStream(socket.getOutputStream()); DataInputStream dis=new DataInputStream(socket.getInputStream()); byte[] resp=new byte[1024];

System.out.println(”Case1:执行测试,对出生日期为空字符串的逻辑进行修正,若为空字符串,则将原有的出生日期清空,设置为默认值1800-01-01“); String UBirthday=” “;

byte[] setuserinfomsg1=PackMsg.SetUserInfoMsg_Birthday(USkyid, UBirthday);

dos.write(setuserinfomsg1);dis.read(resp);

int respcode2=ByteUtil.bytes2int2(resp, 40, 4);

System.out.println(”Respcode:”+respcode2);

assertEquals (”Respcode Error!”,200,respcode2);

Thread.sleep(1000);

assertEquals (”Birthday

Error!”,”1800-01-01″,DBUtil.PgDBSelect(”select birthday from skyups.tbl_ups_user_info where skyid=”+USkyid));

dos.flush();dis.close();socket.close();

}

@After

public void tearDown() throws Exception

System.out.println(”TearDown:恢复测试环境,删除所有用户信息,包括postgres数据库和casandra的数据“);

DBUtil.PgDBUpdate(”delete from skyups.tbl_ups_user_info where skyid=”+USkyid+”or skyid=”+USkyid2);

DBUtil.CassandraRemove(USkyid);

DBUtil.CassandraRemove(USkyid2);

Thread.sleep(1000);

}

标签:dbutil、java 10 views | 发表评论

Java字节流处理的方法库ByteUtil

2010年07月16日 13:15 | 分类:测试开发蒋 刚毅

随着项目经验的积累,我们测试部的测试方法库也慢慢的建立和完善,目前的方法库主要包括:

a.ByteUtil:byte字节流处理、转换的方法,主要应用于TCP编程

b.DBUtil:Oracle、Postegres、Caasndra等数据库的访问执行方法 c.EncryptionUtil:加密算法,包括md5编码等。

后续还会继续完善各种协议的方法库,并在推广并公测一段时间后将以jar包的方式提供API接口调用。

1.将不同的byte[]字节数组流打包成一个字节数组

public static byte[] pack(byte[] agrs) throws IOException{ ByteArrayOutputStream bout = new ByteArrayOutputStream(); for(byte[] b:agrs){

bout.write(b);

}

byte[] buff = bout.toByteArray();

return buff;

}

2.在byte字节流中搜索指定字节流的位置,采用KMP算法实现。

/**取到字节流中指定字节流的位置

* The Knuth-Morris-Pratt Pattern Matching Algorithm can be used to search a byte array.

* Search the data byte array for the first occurrence

* of the byte array pattern.

*/

public static int indexOf(byte[] data, byte[] pattern) {

int[] failure = computeFailure(pattern);

int j = 0;

for (int i = 0; i < data.length; i++) {

while (j > 0 && pattern[j] != data[i]) {

j = failure[j - 1];

}

if (pattern[j] == data[i]) {

j++;

}

if (j == pattern.length) {

return i + 1;

//return i – pattern.length + 1;

}

}

return -1;

}

/**

* Computes the failure function using a boot-strapping process, * where the pattern is matched against itself.

*/

private static int[] computeFailure(byte[] pattern) {

int[] failure = new int[pattern.length];

int j = 0;

for (int i = 1; i < pattern.length; i++) {

while (j>0 && pattern[j] != pattern[i]) {

j = failure[j - 1];

}

if (pattern[j] == pattern[i]) {

j++;

}

failure[i] = j;

}

return failure;

}

3.将字节流的详细信息显示

//HEX字节流显示

public static String dumpBytesAsHEX(byte[] bytes) {

int idx = 0;

String s = “”;

StringBuilder body = new StringBuilder();

for (int i=0;i<1024&&i<bytes.length;i++) {

byte b = bytes[i];

int hex = ((int) b) & 0xff;

String shex = Integer.toHexString(hex).toUpperCase();

if (1 == shex.length()) {

body.append(”0″);

}

body.append(shex);

body.append(” “);

idx++;

// if (16 == idx) {

// s = body.toString();

// body = new StringBuilder();

// idx = 0;

// }

}

if (idx != 0) {

s = body.toString();

}

return s;

}

4.将整型转换成指定长度的数组字节流

public static byte[] int2bytes(int integer, int len) {

// if (integer < 0) { throw new IllegalArgumentException(”Can not cast negative to bytes : ” + integer); }

ByteArrayOutputStream bo = new ByteArrayOutputStream();

for (int i = 0; i < len; i++) {

bo.write(integer);

integer = integer >> 8;

}

byte[] res=reversEndian(bo.toByteArray(),len);

return res;

}

private static byte[] reversEndian(byte str[],int len) {

byte b;

byte res[]=new byte[len];

for(int i=0;i<len;i++)

{

b=str[i];

res[len-i-1]=b;

}

return res;

}

5.将整型转换成TLV方式的字节数组流

public static byte[] int2TLVbytes(int tag,int value,int len) throws IOException{

byte[] tag1=int2bytes(tag,4);

byte[] length1=int2bytes(len,4);

byte[] value1=int2bytes(value,len);

byte[] buff=pack(tag1,length1,value1);

return buff;

}

6.将UTF-8的string转换成指定长度的字节数组流,不足部分补fillByte(如0×00)

public static byte[] string2bytes(String source, int length,byte fillByte) {

byte[] dst = new byte[length];

if (source == null) {

for (int i = 0; i < length; i++) {

dst[i] = fillByte;

}

return dst;

}

try {

byte[] b = source.getBytes(”UTF-8″);

if (b.length > length) {

System.arraycopy(b, 0, dst, 0, length);

} else {

System.arraycopy(b, 0, dst, 0, b.length);

for (int i = dst.length; i < length; i++) {

dst[i] = fillByte;

}

}

} catch (Exception e) {

for (int i = 0; i < length; i++) {

dst[i] = fillByte;

}

}

return dst;

}

7.将string转换成TLV编码方式的字节数组流

public static byte[] string2TLVbytes(int tag,String value) throws IOException{

int length=value.length();

byte[] tag1=int2bytes(tag,4);

byte[] length1=int2bytes(length,4);

byte[] value1=string2bytes(value,value.length(),(byte)0×00); byte[] buff=pack(tag1,length1,value1);

return buff;

}

8.将字节流转换成UTF-8字符串

public static String bytes2UTF8string(byte source[]) {

String dst = “”;

try {

dst = (new String(source, “UTF-8″));

} catch (UnsupportedEncodingException e) {

dst = “”;

}

return dst;

}

9.将字节流中的指定字节段转换成UTF-8字符型

public static String bytes2UTF8string2(byte b[],int offset,int len){ byte[] a=new byte[len];

for (int i=0;i<len;i++){

a[i]=b[offset];

offset++;

}

return bytes2UTF8string(a);

}

10.将字节流数据转换成整型

public static int bytes2int(byte b[]) {

int s = 0;

for (int i = 0; i < b.length; i++) {

s = s | ((b[i] & 0xff) << ((b.length – i – 1) * 8)); }

return s;

}

11.将字节流中的指定字节段转换成整型

public static int bytes2int2(byte b[],int offset,int len){ byte[] respcode=new byte[len];

for (int i=0;i<len;i++){

respcode[i]=b[offset];

offset++;

}

return bytes2int(respcode);

}

本文来源:https://www.bwwdw.com/article/mjz1.html

Top