使用 JDBC 从 MySQL db 读取图像,适用于 Android:
import java.sql.DriverManager;
import java.util.ArrayList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.mysql.jdbc.Blob;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
/**
*
* Loads products from external MySql database, registered on db4free.net
*
* @author Rodion Altshuler
*
*/
public class CatalogDBSource implements CatalogSource{
Connection conn=null;
String userName = "???";
String password = "???";
String url = "jdbc:mysql://???";
/**
* Set this flag=true before calling getProducts(), for example, in order to make several requests to DB
* without re-opening connection each time
*/
public boolean flag_closeConnection=true; //if set to false, connection after getProducts() will retain opened
/**gets products from external DB
* needs INTERNET permission and MySQL driver
*/
@Override
public ArrayList<Product> getProducts() {
Thread getProductsThread = new Thread(new Runnable(){
@Override
public void run(){
try {
if (conn==null) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = (Connection) DriverManager.getConnection(url, userName, password);
}
Statement s = (Statement) conn.createStatement();
//String qry = "SELECT _ID, DISH_ID, DISH_NAME, DISH_CATEGORY, DISH_IMG FROM MENU";
String qry = "SELECT _ID, DISH_NAME, DISH_IMG FROM MENU";
s.executeQuery(qry);
ResultSet rs = null;
rs = (ResultSet) s.getResultSet();
while (rs.next()) {
int id = rs.getInt("_ID");
String productName = rs.getString("DISH_NAME");
Blob b = (Blob) rs.getBlob("DISH_IMG");
Bitmap productImg = bitmapFromBlob(b);
Product p = new Product(id, productName, productImg, "");
//adding new item in ArrayList<Product> products, declared in interface CatalogSource
products.add(p);
}
rs.close();
s.close();
if (flag_closeConnection) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
getProductsThread.start();
try {
getProductsThread.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
return products;
}
/**
* Converts Blob to Bitmap
* @param b Blob object should be converted to Bitmap
* @return Bitmap object
*/
static Bitmap bitmapFromBlob(Blob b) {
Bitmap bitmap=null;
try {
byte[] temp = b.getBytes(1,(int) b.length());
bitmap = BitmapFactory.decodeByteArray(temp,0, temp.length);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
}