实体类:UserInfo.java
package my.db
import java.io.Serializable
import android.graphics.drawable.Drawable
public class UserInfo implements Serializable {
public static final String ID = "_id"
public static final String USERID = "userId"
public static final String TOKEN = "token"
public static final String TOKENSECRET = "tokenSecret"
public static final String USERNAME = "userName"
public static final String USERICON = "userIcon"
private String id
private String userId// 用户id
private String token
private String tokenSecret
private String userName
private Drawable userIcon
//getter and setter省略
}
SqliteHelper类:
package my.db
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteDatabase.CursorFactory
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
public class SqliteHelper extends SQLiteOpenHelper{
//用来保存UserID、Access Token、Access Secret的表名
public static final String TB_NAME= "users"
public SqliteHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version)
}
//创建表
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL( "CREATE TABLE IF NOT EXISTS "+
TB_NAME+ "("+
UserInfo. ID+ " integer primary key,"+
UserInfo. USERID+ " varchar,"+
UserInfo. TOKEN+ " varchar,"+
UserInfo. TOKENSECRET+ " varchar,"+
UserInfo. USERNAME+ " varchar,"+
UserInfo. USERICON+ " blob"+
")"
)
Log. e("Database" ,"onCreate" )
}
//更新表
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL( "DROP TABLE IF EXISTS " + TB_NAME )
onCreate(db)
Log. e("Database" ,"onUpgrade" )
}
//更新列
public void updateColumn(SQLiteDatabase db, String oldColumn, String newColumn, String typeColumn){
try{
db.execSQL( "ALTER TABLE " +
TB_NAME + " CHANGE " +
oldColumn + " "+ newColumn +
" " + typeColumn
)
} catch(Exception e){
e.printStackTrace()
}
}
}
CRUD类DataHelper:
package my.db
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.ArrayList
import java.util.List
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.util.Log
public class DataHelper {
// 数据库名称
private static String DB_NAME = "weibo.db"
// 数据库版本
private static int DB_VERSION = 2
private SQLiteDatabase db
private SqliteHelper dbHelper
public DataHelper(Context context) {
dbHelper = new SqliteHelper(context, DB_NAME, null, DB_VERSION )
db = dbHelper.getWritableDatabase()
}
public void Close() {
db.close()
dbHelper.close()
}
// 获取users表中的UserID、Access Token、Access Secret的记录
public List<UserInfo>GetUserList(Boolean isSimple) {
List<UserInfo>userList = new ArrayList<UserInfo>()
Cursor cursor = db.query(SqliteHelper. TB_NAME, null, null , null, null,
null, UserInfo. ID + " DESC")
cursor.moveToFirst()
while (!cursor.isAfterLast() &&(cursor.getString(1) != null )) {
UserInfo user = new UserInfo()
user.setId(cursor.getString(0))
user.setUserId(cursor.getString(1))
user.setToken(cursor.getString(2))
user.setTokenSecret(cursor.getString(3))
if (!isSimple) {
user.setUserName(cursor.getString(4))
ByteArrayInputStream stream = new ByteArrayInputStream(cursor.getBlob(5))
Drawable icon = Drawable.createFromStream(stream, "image")
user.setUserIcon(icon)
}
userList.add(user)
cursor.moveToNext()
}
cursor.close()
return userList
}
// 判断users表中的是否包含某个UserID的记录
public Boolean HaveUserInfo(String UserId) {
Boolean b = false
Cursor cursor = db.query(SqliteHelper. TB_NAME, null, UserInfo.USERID
+ "=?", new String[]{UserId}, null, null, null )
b = cursor.moveToFirst()
Log. e("HaveUserInfo", b.toString())
cursor.close()
return b
}
// 更新users表的记录,根据UserId更新用户昵称和用户图标
public int UpdateUserInfo(String userName, Bitmap userIcon, String UserId) {
ContentValues values = new ContentValues()
values.put(UserInfo. USERNAME, userName)
// BLOB类型
final ByteArrayOutputStream os = new ByteArrayOutputStream()
// 将Bitmap压缩成PNG编码,质量为100%存储
userIcon.compress(Bitmap.CompressFormat. PNG, 100, os)
// 构造SQLite的Content对象,这里也可以使用raw
values.put(UserInfo. USERICON, os.toByteArray())
int id = db.update(SqliteHelper. TB_NAME, values, UserInfo.USERID + "=?" , new String[]{UserId})
Log. e("UpdateUserInfo2", id + "")
return id
}
// 更新users表的记录
public int UpdateUserInfo(UserInfo user) {
ContentValues values = new ContentValues()
values.put(UserInfo. USERID, user.getUserId())
values.put(UserInfo. TOKEN, user.getToken())
values.put(UserInfo. TOKENSECRET, user.getTokenSecret())
int id = db.update(SqliteHelper. TB_NAME, values, UserInfo.USERID + "="
+ user.getUserId(), null)
Log. e("UpdateUserInfo", id + "")
return id
}
// 添加users表的记录
public Long SaveUserInfo(UserInfo user) {
ContentValues values = new ContentValues()
values.put(UserInfo. USERID, user.getUserId())
values.put(UserInfo. TOKEN, user.getToken())
values.put(UserInfo. TOKENSECRET, user.getTokenSecret())
Long uid = db.insert(SqliteHelper. TB_NAME, UserInfo.ID, values)
Log. e("SaveUserInfo", uid + "")
return uid
}
// 添加users表的记录
public Long SaveUserInfo(UserInfo user, byte[] icon) {
ContentValues values = new ContentValues()
values.put(UserInfo. USERID, user.getUserId())
values.put(UserInfo. USERNAME, user.getUserName())
values.put(UserInfo. TOKEN, user.getToken())
values.put(UserInfo. TOKENSECRET, user.getTokenSecret())
if(icon!= null){
values.put(UserInfo. USERICON, icon)
}
Long uid = db.insert(SqliteHelper. TB_NAME, UserInfo.ID, values)
Log. e("SaveUserInfo", uid + "")
return uid
}
// 删除users表的记录
public int DelUserInfo(String UserId) {
int id = db.delete(SqliteHelper. TB_NAME,
UserInfo. USERID + "=?", new String[]{UserId})
Log. e("DelUserInfo", id + "")
return id
}
public static UserInfo getUserByName(String userName,List<UserInfo>userList){
UserInfo userInfo = null
int size = userList.size()
for( int i=0i<sizei++){
if(userName.equals(userList.get(i).getUserName())){
userInfo = userList.get(i)
break
}
}
return userInfo
}
}
Android中对于SQLite3数据库的 *** 作如下:1、建立数据库
SQLiteDatabasemDatabase
mDatabase
=
openOrCreateDatabase(
"my_sqlite_database.db”,
SQLiteDatabase.CREATE_IF_NECESSARY,
null
)
2、配置属性
mDatabase.setVersion(1)
mDatabase.setLocale(Locate.getDefault())
mDatabase.setLockingEnable(true)
3、建表
CREATETABLE
tb_test
(
idINTEGER
PRIMARYKEY
AUTOINCREMENT,
firstnameTEXT,
lastnameTEXT
)
4、数据库 *** 作
insert(Peoplepeople)用来添加一条数据
queryAllData()用来获取全部数据
queryOneData(long
id)根据id获取一条数据
deleteAllData()用来删除全部数据
deleteOneData(long
id)根据id删除一条数据
updateOneData(long
id
,
People
people)根据id更新一条数据
有点多请耐心看完。希望能帮助你,还请及时采纳谢谢。
一.前言
android连接数据库的方式有两种,第一种是通过连接服务器,再由服务器读取数据库来实现数据的增删改查,这也是我们常用的方式。第二种方式是android直接连接数据库,这种方式非常耗手机内存,而且容易被反编译造成安全隐患,所以在实际项目中不推荐使用。
二.准备工作
1.加载外部jar包
在Android工程中要使用jdbc的话,要导入jdbc的外部jar包,因为在Java的jdk中并没有jdbc的api,我使用的jar包是mysql-connector-java-5.1.18-bin.jar包,网络上有使用mysql-connector-java-5.1.18-bin.jar包的,自己去用的时候发现不兼容,所以下载了比较新版本的,jar包可以去官网下载,也可以去百度,有很多前人们上传的。
2.导入jar包的方式
方式一:
可以在项目的build.gradle文件中直接添加如下语句导入
compile files('libs/mysql-connector-java-5.1.18-bin.jar')
方式二:下载jar包复制到项目的libs目录下,然后右键复制过来的jar包Add as libs
三.建立数据库连接
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_jdbc)
new Thread(runnable).start()
}
Handler myHandler=new Handler(){
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg)
Bundle data=new Bundle()
data=msg.getData()
//System.out.println("id:"+data.get("id").toString()) //输出第n行,列名为“id”的值
Log.e("TAG","id:"+data.get("id").toString())
TextView tv= (TextView) findViewById(R.id.jdbc)
//System.out.println("content:"+data.get("content").toString())
}
}
Runnable runnable=new Runnable() {
private Connection con = null
@Override
public void run() {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.jdbc.Driver")
//引用代码此处需要修改,address为数据IP,Port为端口号,DBName为数据名称,UserName为数据库登录账户,Password为数据库登录密码
con =
//DriverManager.getConnection("jdbc:mysql://192.168.1.202:3306/b2b", "root", "")
DriverManager.getConnection("jdbc:mysql://http://192.168.1.100/phpmyadmin/index.php:8086/b2b",
UserName,Password)
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
try {
testConnection(con) //测试数据库连接
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
public void testConnection(Connection con1) throws java.sql.SQLException {
try {
String sql = "select * from ecs_users" //查询表名为“oner_alarm”的所有内容
Statement stmt = con1.createStatement() //创建Statement
ResultSet rs = stmt.executeQuery(sql) //ResultSet类似Cursor
//<code>ResultSet</code>最初指向第一行
Bundle bundle=new Bundle()
while (rs.next()) {
bundle.clear()
bundle.putString("id",rs.getString("userid"))
//bundle.putString("content",rs.getString("content"))
Message msg=new Message()
msg.setData(bundle)
myHandler.sendMessage(msg)
}
rs.close()
stmt.close()
} catch (SQLException e) {
} finally {
if (con1 != null)
try {
con1.close()
} catch (SQLException e) {}
}
}
}
注意:
在Android4.0之后,不允许在主线程中进行比较耗时的 *** 作(连接数据库就属于比较耗时的 *** 作),需要开一个新的线程来处理这种耗时的 *** 作,没新线程时,一直就是程序直接退出,开了一个新线程处理直接,就没问题了。
当然,连接数据库是需要网络的,千万别忘了添加访问网络权限:
<uses-permission android:name=”android.permission.INTERNET”/>
四.bug点
1.导入的jar包一定要正确
2.连接数据库一定要开启新线程
3.数据库的IP一定要是可以ping通的,局域网地址手机是访问不了的
4.数据库所在的服务器是否开了防火墙,阻止了访问
————————————————
版权声明:本文为CSDN博主「shuaiyou_comon」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/shuaiyou_comon/article/details/75647355
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)