紧接上一篇介绍DataHelper的用法。

    DataHelper在使用过程中最好的就配合BindObject类一起使用。下面附上BindObject类的源码:
BindObject
  1public class BindObject
  2    {
  3        绑定#region 绑定
  4        
  5        public static object[] BindObjectToArray(Type instanceType, IDataReader reader)
  6        {
  7            try
  8            {
  9                PropertyInfo [] properties = instanceType.GetProperties();
 10                ArrayList items = new ArrayList();
 11                Hashtable fieldName = new Hashtable();
 12                int fieldCount = reader.FieldCount;
 13                for (int i = 0; i < fieldCount; i++)
 14                {
 15                    string name = reader.GetName(i).ToString().ToLower();
 16                    fieldName.Add(name, i);
 17                }

 18                while (reader.Read())
 19                {
 20                    object instance = Activator.CreateInstance(instanceType);
 21                    foreach (PropertyInfo property in properties)
 22                    {
 23                        object[] attributes = property.GetCustomAttributes(typeof(MappingFieldAttribute), false);
 24                        object[] encoders = property.GetCustomAttributes(typeof(CharacterEncodeAttribute), false);
 25                        string aName = string.Empty;
 26                        CharacterEncodeAttribute encoder = null;
 27                        if(attributes != null && attributes.Length > 0)
 28                        {
 29                            MappingFieldAttribute mapping = attributes[0as MappingFieldAttribute;
 30                            aName = mapping.FieldName.ToLower();
 31                        }

 32                        if (encoders != null && encoders.Length > 0)
 33                        {
 34                            encoder = encoders[0as CharacterEncodeAttribute;
 35                        }

 36                        string pName = property.Name.Trim().ToLower();
 37                        int index = -1;
 38                        if (fieldName.ContainsKey(pName))
 39                            index = (int)fieldName[pName];
 40                        else if (aName != string.Empty && fieldName.ContainsKey(aName))
 41                            index = (int)fieldName[aName];
 42                        if (index >= 0)
 43                        {
 44                            object obj = reader[index];
 45                            Type propertyType = property.PropertyType;
 46                            if (propertyType.IsArray || propertyType.IsInterface)
 47                            {
 48                                continue;
 49                            }

 50                            else if (property.PropertyType.IsEnum)
 51                            {
 52                                if(obj != null && obj != DBNull.Value)
 53                                    property.SetValue(instance, Enum.Parse(property.PropertyType, obj.ToString(), true), null);
 54                            }

 55                            else
 56                            {
 57                                if(obj != null && obj != DBNull.Value)
 58                                {
 59                                    if(property.PropertyType == typeof(string&& encoder != null)
 60                                        property.SetValue(instance, encoder.Encode(obj.ToString()), null);
 61                                    else
 62                                        property.SetValue(instance, Convert.ChangeType(obj, property.PropertyType), null);
 63                                }
                                 
 67                            }

 68                        }

 69                    }

 70                    items.Add(instance);
 71                }

 72                if (!reader.IsClosed)
 73                    reader.Close();
 74                object [] instances = (object[])Array.CreateInstance(instanceType, items.Count);
 75                for(int i = 0; i < items.Count; i++)
 76                {
 77                    //string str=  "<![CDATA[" + items[i].ToString() +"]]>";
 78                    instances[i] = items[i];
 79                }

 80                return instances;
 81            }

 82            catch(Exception ex)
 83            {
 84                throw ex;
 85            }

 86        }

 87
 88        
 89        /**//// <summary>
 90        /// 绑定
 91        /// </summary>
 92        /// <param name="instanceType"></param>
 93        /// <param name="reader"></param>
 94        /// <returns></returns>

 95        public static IList BindObjectToInstance(Type instanceType, IDataReader reader)
 96        {
 97            PropertyInfo [] properties = instanceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
 98            ArrayList items = new ArrayList();
 99            Hashtable fieldName = new Hashtable();
100            int fieldCount = reader.FieldCount;
101            for (int i = 0; i < fieldCount; i++)
102            {
103                string name = reader.GetName(i).ToString().ToLower();
104                fieldName.Add(name, i);
105            }

106            while (reader.Read())
107            {
108                object instance = Activator.CreateInstance(instanceType);
109                foreach (PropertyInfo property in properties)
110                {
111                    string pName = property.Name.Trim().ToLower();
112                    int index = -1;
113                    if (fieldName.ContainsKey(pName))
114                        index = (int)fieldName[pName];
115                    if (index >= 0)
116                    {
117                        object obj = reader[index];
118                        Type propertyType = property.PropertyType;
119                        if (propertyType.IsArray || propertyType.IsInterface)
120                        {
121                            continue;
122                        }

123                        else if (property.PropertyType.IsEnum)
124                        {
125                            if(obj != null && obj != DBNull.Value)
126                                property.SetValue(instance, Enum.Parse(property.PropertyType, obj.ToString(), true), null);
127                        }

128                        else
129                        {
130                            if(obj != null && obj != DBNull.Value)
131                                property.SetValue(instance, Convert.ChangeType(obj, property.PropertyType), null);
132                        }

133                    }

134                }

135                items.Add(instance);
136            }

137            if (!reader.IsClosed)
138                reader.Close();
139            return items;
140        }

141        #endregion

142    }

下面再给出一个结合两者使用的方法:

Test(int id)
 1 public IList Test(int id)
 2        {
 3            using (DataHelper helper = new DataHelper("server=localhost;database=pubs;uid=sa;pwd=111;"))
 4            {
 5                IDataReader reader = helper.CreateQuery(@"Select * From Table1 Where id=:id")
 6                    .SetInt32("id", id)
 7                    .ExecuteReader();
 8                return BindObject.BindObjectToInstance(typeof(Table1), reader);
 9            }

10        }

这个操作DataHelper的方法比较简单一看就明白我这里就不详细介绍了,简单的介绍下BindObject类,它是运用了反射的方式来对实体中的字段进行读取比较,然后赋值的,所以实体中的字段必须对应我们所写sql中的列。
个人觉得这些都没啥技术含量,其实真正重要是思想,是一种解决问题的方法。
注:这里的BindObject类里还涉及到自定义属性的问题,直接拷贝进去是运行不了,在下篇里将继续附上该类代码。并介绍其用处。呵呵。。。
本人水平有限,希望能迎来大家的“砖头”,越多越好咯。。。

转载于:https://www.cnblogs.com/strayromeo/archive/2008/12/09/1351459.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要在 Android Studio 中创建一个 SQLite 数据库。 1. 在项目中创建一个新的文件夹,命名为“database”或者其他你喜欢的名称。 2. 在该文件夹下创建一个新的类,命名为“DatabaseHelper”。 3. 在该类中,继承“SQLiteOpenHelper”类,并重写“onCreate”和“onUpgrade”方法。 ```java public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "myDatabase.db"; private static final int DATABASE_VERSION = 1; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // 创建表格 String sql = "CREATE TABLE IF NOT EXISTS student (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT, " + "age INTEGER)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 更新表格 String sql = "DROP TABLE IF EXISTS student"; db.execSQL(sql); onCreate(db); } } ``` 在这个例子中,我们创建了一个名为“myDatabase.db”的数据库,以及一个名为“student”的表格(包含三个字段:_id、name、age)。如果该表格不存在,则在“onCreate”方法中创建该表格。如果该表格已经存在,但版本号发生了变化,则在“onUpgrade”方法中更新该表格。 接下来,我们需要创建一个“DataHelper”类来实现数据库的增删改查功能。 ```java public class DataHelper { private DatabaseHelper dbHelper; private SQLiteDatabase db; public DataHelper(Context context) { dbHelper = new DatabaseHelper(context); db = dbHelper.getWritableDatabase(); } public void insert(String name, int age) { ContentValues cv = new ContentValues(); cv.put("name", name); cv.put("age", age); db.insert("student", null, cv); } public void update(int id, String name, int age) { ContentValues cv = new ContentValues(); cv.put("name", name); cv.put("age", age); db.update("student", cv, "_id = ?", new String[] { String.valueOf(id) }); } public void delete(int id) { db.delete("student", "_id = ?", new String[] { String.valueOf(id) }); } public Cursor queryAll() { Cursor cursor = db.query("student", null, null, null, null, null, null); return cursor; } public Cursor queryById(int id) { Cursor cursor = db.query("student", null, "_id = ?", new String[] { String.valueOf(id) }, null, null, null); return cursor; } public void close() { db.close(); dbHelper.close(); } } ``` 在这个例子中,我们创建了一个“DataHelper”类,用于实现增删改查功能。我们在该类中创建了以下方法: 1. “insert”方法:用于向表格中插入数据。 2. “update”方法:用于更新表格中的数据。 3. “delete”方法:用于删除表格中的数据。 4. “queryAll”方法:用于查询表格中的所有数据。 5. “queryById”方法:用于根据ID查询表格中的数据。 6. “close”方法:用于关闭数据库连接。 最后,我们可以在 Activity 中调用这些方法来实现具体的操作。例如: ```java DataHelper dataHelper = new DataHelper(this); dataHelper.insert("Tom", 20); // 插入一条数据 dataHelper.update(1, "Jerry", 22); // 更新一条数据 dataHelper.delete(1); // 删除一条数据 Cursor cursor = dataHelper.queryAll(); // 查询所有数据 while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.d("SQLite", "_id=" + id + ", name=" + name + ", age=" + age); } cursor.close(); dataHelper.close(); // 关闭数据库连接 ``` 这样,就可以实现一个简单的 SQLite 数据库的增删改查功能了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值