怎样获取 SQLite 数据库中 int 类型的数据?

如图片所示,在数据库里定义了 int id。读取时报错: int id=cursor.getInt(curs图片说明upload/201707/22/1500655576_804790图片说明et/upload/201707/22/1500655601_55图片说明3408.png).png)or.getColumnIndex("id"));

2个回答

数据库的类型如果不是主键都设置为char 可以选择用int来接收

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

如何从sqlite数据库中获取数据并显示在listview中?

在登录页面后,我想在listview中把Apple显示成A,Boy显示成B等等,直到F。但是在程序中当我完全登录后,只有登录表成功创建,主菜单还是没有创建。 我想在test database中创建主菜单,然后我想从主菜单表(mainmenu table)中获取数据再显示在listview中。 我使用了下面的代码: if(username.length()>0&&password.length()>0) { SQLiteAdapter db=new SQLiteAdapter(Main.this); db.openToWrite(); if(db.Login(username,password)) { System.out.println("goutham"); Intent intent=new Intent(getApplicationContext(),ExampleActivity.class); startActivity(intent); } SQLiteAdapter.java } public Cursor queueAll() { String[] columns = new String[] { KEY_ID, KEY_CONTENT }; Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null, null, null, null, null); return cursor; } private static class SQLiteHelper extends SQLiteOpenHelper { public SQLiteHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(SCRIPT_CREATE_DATABASE); db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } } public long AddUser(String username, String password) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_USERNAME, username); initialValues.put(KEY_PASSWORD, password); return sqLiteDatabase.insert(DATABASE_TABLE, null, initialValues); } public boolean Login(String username, String password) { // TODO Auto-generated method stub Cursor mCursor = sqLiteDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE username=? AND password=?", new String[] { username, password }); if (mCursor != null) { if (mCursor.getCount() > 0) { return true; } } return false; } } ExampleActivity.java public class ExampleActivity extends Activity { private SQLiteAdapter mySQLiteAdapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ListView listContent = (ListView) findViewById(R.id.contentlist); /* * Create/Open a SQLite database and fill with dummy content and close * it */ mySQLiteAdapter = new SQLiteAdapter(this); mySQLiteAdapter.openToWrite(); // mySQLiteAdapter.deleteAll(); mySQLiteAdapter.insert("A for Apply"); mySQLiteAdapter.insert("B for Boy"); mySQLiteAdapter.insert("C for Cat"); mySQLiteAdapter.insert("D for Dog"); mySQLiteAdapter.insert("E for Egg"); mySQLiteAdapter.insert("F for Fish"); mySQLiteAdapter.close(); /* * Open the same SQLite database and read all it's content. */ mySQLiteAdapter = new SQLiteAdapter(this); mySQLiteAdapter.openToRead(); Cursor cursor = mySQLiteAdapter.queueAll(); startManagingCursor(cursor); String[] from = new String[] { SQLiteAdapter.KEY_CONTENT }; int[] to = new int[] { R.id.text }; SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to); listContent.setAdapter(cursorAdapter); mySQLiteAdapter.close(); } } 运行程序后,登录表在数据库中创建了,但是主菜单表没有创建。运行程序后,显示一个错误: sqlite returned code=1 no such a table in MY_TABLE

如何在Sqlite数据库中插入数据列表?

我创建了一个简单的数据库用来插入数据库列表,但是当我想把数据发送到数据库时,有下面的错误: 08-28 15:30:43.015: ERROR/Database(822): Failure 1 (no such column: Sharma) on 0x276e50 when preparing 'INSERT INTO friends Values(Sharma,SaiGeetha,18);"" 相关的代码: sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null); ArrayList<String>FirstName = new ArrayList<String>(); ArrayList<String>LastName = new ArrayList<String>(); ArrayList<Integer >Age = new ArrayList<Integer>(); FirstName.add("SaiGeetha"); FirstName.add("Vivek"); FirstName.add("Rahul"); LastName.add("Sharma"); LastName.add("Lilani"); LastName.add("Lami"); Age.add(18); Age.add(20); Age.add(23); sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " + SAMPLE_TABLE_NAME + " (LastName VARCHAR, FirstName VARCHAR," + " Age INT(3));"); for(int i=0;i<3;i++) { sampleDB.execSQL("INSERT INTO " + enter code here SAMPLE_TABLE_NAME + " Values("+LastName.get(i)+","+FirstName.get(i)+","+Age.get(i)+");"+"\"\""); } /*sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ('Makam','Sai Geetha','India',25);"); sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ('Chittur','Raman','India',25);"); sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ('Solutions','Collabera','India',20);");*/ Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " + SAMPLE_TABLE_NAME + " where Age > 10 LIMIT 5", null); if (c != null ) { if (c.moveToFirst()) { do { String firstName = c.getString(c.getColumnIndex("FirstName")); int age = c.getInt(c.getColumnIndex("Age")); Log.e("---LIST FROM DATABASE--","---VALUE---"+firstName); Log.e("---LIST FROM DATABASE--","---VALUE---"+age ); }while (c.moveToNext()); } } sampleDB.close(); } catch (SQLiteException se ) { Log.e(getClass().getSimpleName(), "Could not create or Open the database"); } finally { if (sampleDB != null) sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME); sampleDB.close(); } } 哪里的问题呢?

使用go从我的sqlite数据库获取最新记录

<div class="post-text" itemprop="text"> <p>I want to query my sqlite db to get the last id in my book table then insert the data with the last id + 1. I am new to Go and I can't figure out how to set my lastid int variable. Any help would be greatly appreciated. </p> <pre><code>func getBookLastID() { var lastid int err := db.QueryRow("select max(id) from books").Scan(&amp;lastid) fmt.Println(lastid) return (lastid + 1) } func insertBook(name, author string, pages int, publicationDate time.Time) (int, error) { //Create var bookID int var lastid int lastid = getBookLastID() err := db.QueryRow(`INSERT INTO books(id, name, author, pages, publication_date) VALUES($1, $2, $3, $4, $5)`, lastid, name, author, pages, publicationDate).Scan(&amp;bookID) if err != nil { return 0, err } fmt.Printf("Last inserted ID: %v ", bookID) return bookID, err } </code></pre> </div>

C#关于sqlite数据库问题,大神来看看

``` namespace QQLite.GuessFeng { /// <summary> /// 说明:这是一个针对System.Data.SQLite的数据库常规操作封装的通用类。 /// 更新时间:2014-10-31 /// </summary> public class SQLiteDBHelper//SQLiteDBHelper { public static string DataSource = string.Format("Data Source={0};Pooling=true;FailIfMissing=false", Path.Combine(D:\\, "GuessFeng.db")); public static string dbpath = D:\\ + "GuessFeng.db"; private string connectionString = string.Empty; #region 数据库连接必要条件参数 private SQLiteConnection dbConnection = null; /// <summary> /// 数据库连接 /// </summary> public SQLiteConnection DbConnection { get { if (this.dbConnection == null) { // 若没打开,就变成自动打开关闭的 this.Open(); this.AutoOpenClose = true; } return this.dbConnection; } set { this.dbConnection = value; } } private SQLiteCommand dbCommand = null; /// <summary> /// 命令 /// </summary> public SQLiteCommand DbCommand { get { return this.dbCommand; } set { this.dbCommand = value; } } private SQLiteDataAdapter dbDataAdapter = null; /// <summary> /// 数据库适配器 /// </summary> public SQLiteDataAdapter DbDataAdapter { get { return this.dbDataAdapter; } set { this.dbDataAdapter = value; } } /// <summary> /// 数据库连接 /// </summary> public string ConnectionString { get { return this.connectionString; } set { this.connectionString = value; } } private SQLiteTransaction dbTransaction = null; private bool inTransaction = false; /// <summary> /// 是否已采用事务 /// </summary> public bool InTransaction { get { return this.inTransaction; } set { this.inTransaction = value; } } private bool autoOpenClose = false; /// <summary> /// 默认打开关闭数据库选项(默认为否) /// </summary> public bool AutoOpenClose { get { return autoOpenClose; } set { autoOpenClose = value; } } #endregion /// <summary> /// 构造函数 /// </summary> /// <param name="dbPath">SQLite数据库文件路径</param> public SQLiteDBHelper() { // string dbPath = Client.BasePath + @"QQ\" + Client.QQ + @"\DataBase\QQLite.Plugin.VipwarrantPlugin.db"; this.connectionString = DataSource; } /// <summary> /// 这时主要的获取数据库连接的方法 /// </summary> /// <returns>数据库连接</returns> public IDbConnection Open() { this.Open(this.ConnectionString); return this.dbConnection; } /// <summary> /// 获得新的数据库连接 /// </summary> /// <param name="connectionString">数据库连接字符串</param> /// <returns>数据库连接</returns> public IDbConnection Open(string connectionString) { // 若是空的话才打开 if (this.dbConnection == null || this.dbConnection.State == ConnectionState.Closed) { this.ConnectionString = connectionString; this.dbConnection = new SQLiteConnection(this.ConnectionString); this.dbConnection.Open(); } this.AutoOpenClose = false; return this.dbConnection; } #region 建立本地数据库 /// <summary> /// 创建SQLite数据库文件 /// </summary> /// <param name="dbPath">要创建的SQLite数据库文件路径</param> public void CreateDB() { if (!File.Exists(dbpath)) { // 自动打开 if (this.DbConnection == null) { this.AutoOpenClose = true; this.Open(); } else if (this.DbConnection.State == ConnectionState.Closed) { this.Open(); } this.dbCommand = this.DbConnection.CreateCommand(); this.dbCommand.CommandText = "CREATE TABLE [DBVersion] ([Version] NVARCHAR(50) NULL);INSERT INTO [DBVersion] (Version) values('4.0.0.0');CREATE TABLE [RanNum] ([Id] INTEGER PRIMARY KEY NOT NULL,[ExternalId] INTEGER NOT NULL,[Num] INTEGER NOT NULL,[LastQQ]INTEGER NULL);CREATE TABLE [Config] ([Id] INTEGER PRIMARY KEY NOT NULL,[Fix] TEXT NULL,[Open] INTEGER NOT NULL,[Deduct] INTEGER NOT NULL,[Award] INTEGER NOT NULL);INSERT INTO [Config] (Fix,Open,Deduct,Award) values('#',10,5,100);CREATE TABLE [Lock] ([Id] INTEGER PRIMARY KEY NOT NULL,[value] TEXT NULL);"; this.dbCommand.ExecuteNonQuery(); //this.dbCommand.CommandText = "DROP TABLE Demo"; //this.dbCommand.ExecuteNonQuery(); } } #endregion /// <summary> /// 对SQLite数据库执行增删改操作,返回受影响的行数。 /// </summary> /// <param name="commandText">要执行的增删改的SQL语句</param> /// <param name="parameters">执行增删改语句所需要的参数,参数必须以它们在SQL语句中的顺序为准</param> /// <returns></returns> public int ExecuteNonQuery(string commandText, SQLiteParameter[] parameters) { // 自动打开 if (this.DbConnection == null) { this.AutoOpenClose = true; this.Open(); } else if (this.DbConnection.State == ConnectionState.Closed) { this.Open(); } this.dbCommand = this.DbConnection.CreateCommand(); this.dbCommand.CommandText = commandText; if (this.dbTransaction != null) { this.dbCommand.Transaction = this.dbTransaction; } if (parameters != null) { this.dbCommand.Parameters.Clear(); for (int i = 0; i < parameters.Length; i++) { this.dbCommand.Parameters.Add(parameters[i]); } } int returnValue = this.dbCommand.ExecuteNonQuery(); // 自动关闭 this.dbCommand.Parameters.Clear(); // 自动关闭 //if (this.AutoOpenClose) //{ // this.Close(); //} return returnValue; } #endregion #region public void Close() 关闭数据库连接 /// <summary> /// 关闭数据库连接 /// </summary> public void Close() { if (this.dbConnection != null) { this.dbConnection.Close(); this.dbConnection.Dispose(); } this.Dispose(); } #endregion #region public void Dispose() 内存回收 /// <summary> /// 内存回收 /// </summary> public void Dispose() { if (this.dbCommand != null) { this.dbCommand.Dispose(); } if (this.dbDataAdapter != null) { this.dbDataAdapter.Dispose(); } this.dbConnection = null; } #endregion } } ``` ``` private void button1_Click(object sender, EventArgs e) { SQLiteDBHelper vdb = new SQLiteDBHelper();//初始化SQLite数据库 string sql = "UPDATE Config SET Fix=@Fix,Open=@Open,Deduct=@Deduct,Award=@Award WHERE (Id=1)";//修改语句 SQLiteParameter[] Config = new SQLiteParameter[]{ new SQLiteParameter("@Fix",text_Fix.Text ), new SQLiteParameter ("@Open",text_Open.Text ), new SQLiteParameter("@Deduct",text_Deduct.Text ), new SQLiteParameter("@Award",text_Award.Text ) }; //MessageBox.Show("保存成功!"); if (vdb.ExecuteNonQuery(sql, Config) > 0) { MessageBox.Show("保存成功!"); } } ``` 为什么点击按钮保存,一点就卡死

AndroidSQLite数据库删除数据后ListView的更新

一款记账的软件,我的数据存储在SQLite中,当我长按item时,弹出对话框并确定删除该item,但是数据库中的删掉了,activity中的listView中该item还在,依理来说是因为我的adapter适配器加载的还是内存中的数据,但是小白还是没有想到好的解决办法,我试了使用广播,但是出现整个页面的item都被删了(数据库的其他还在)。其他的各种办法也都试了还是不行,无奈求助各位看到帖子的大神。讲解的好,我绝对给高分。先谢过各位了。 ![图片说明](https://img-ask.csdn.net/upload/201703/22/1490187215_17835.png) 适配器代码在此: ``` public class CostListAdapter extends BaseAdapter { private List<CostBean> mList; private Context mContext; private LayoutInflater mInflater; public CostListAdapter(Context context, final List<CostBean> list){ mContext = context; mList = list; mInflater = LayoutInflater.from(context); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.zsf.accountbook.MY_BROADCAST"); context.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mList.clear(); mList = list; notifyDataSetChanged(); } },intentFilter); } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null){ holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.list_item,null); holder.mTvCostCategory = (TextView) convertView.findViewById(R.id.tv_category); holder.mTvCostDate = (TextView) convertView.findViewById(R.id.tv_date); holder.mTvCostMoney = (TextView) convertView.findViewById(R.id.tv_money); convertView.setTag(holder); }else { holder = (ViewHolder) convertView.getTag(); } CostBean costBean = mList.get(position);// holder.mTvCostCategory.setText(costBean.costCategory); holder.mTvCostDate.setText(costBean.costDate); holder.mTvCostMoney.setText(costBean.costMoney); return convertView; } private static class ViewHolder{ public TextView mTvCostCategory; public TextView mTvCostDate; public TextView mTvCostMoney; } } ``` ![图片说明](https://img-ask.csdn.net/upload/201703/22/1490187234_665074.png) ![图片说明](https://img-ask.csdn.net/upload/201703/22/1490187852_566687.gif) 漏掉了数据库部分的代码: ![图片说明](https://img-ask.csdn.net/upload/201703/22/1490188335_213349.png)

Android SQLite数据库提取并存储到数组

开发过程中需要将蓝牙设备传给手机的数据存储下来,并能将数据存储在数组中,利用数组中的数据,我需要去描点画图。现在数据库已经创建成功,并且能够存储数据了,但是从数据库提取数据的时候,就无法运行,请大神指教 ``` private SaveDatabaseHelper dbHelper; ArrayList<String> dataList = new ArrayList<String>(); ... dbHelper = new SaveDataHelper(this,"Data.db",null,1); dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("data",data);//data值由蓝牙传入 dbHelper.insert(values); Cursor cursor = dbHelper.query(new String[]{"data"},"data = ?",null,null,null,null); if(cursor != null && cursor.getCount() >0){ while(cursor.moveToNext()){ for(int i = 0 ; i < cursor.getCount();i++){ String data = cursor.getString(cursor.getColumnIndex("data")); dataList.add(data); } } cursor.close(); } ``` 代码是这些,但是程序运行到insert方法之后就没有继续往下运行了,直接跳过了,不知道是什么原因,数据库这边我基础很弱,还请大神指导

Android 通过ContentProvider向SQLite数据库插入数据不成功

我自己写了一个ContentProvider,在执行向SQLiteDatabase数据库中插入一条记录时不成功,打出的log如下: 11-27 02:00:11.696: ERROR/Database(997): android.database.sqlite.SQLiteException: table employee has no column named name: , while compiling: INSERT INTO employee(name) VALUES(?); 我的SQLiteOpenHelper类的派生类如下: [code="java"]package com.hgl.test; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.hgl.test.Employees.Employee; public class DBHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "Employees.db"; private static final int DATABASE_VERSION = 1; public static final String EMPLOYEES_TABLE_NAME = "employee"; // 创建数据库 public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); Log.i("DBHelper Info===================>>>>>>>","this is DBHelper constructer function"); } // 创建时调用,创建一个表 @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub Log.i("DBHelper Info===================>>>>>>>","this is onCreate function"); String createTableSQL = "CREATE TABLE " + EMPLOYEES_TABLE_NAME + "(" + Employee._ID + " INTEGER PRIMARY KEY," + Employee.NAME + " TEXT," + Employee.GENDER + " TEXT," + Employee.AGE + " INTEGER)"; db.execSQL(createTableSQL); Log.d("Create Table=====================>>>>>>>>>>>", "create table " + EMPLOYEES_TABLE_NAME); } // 版本更新时调用 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS "+EMPLOYEES_TABLE_NAME); onCreate(db); } }[/code] 自己的ContentProvider派生类如下: public class MyContentProvider extends ContentProvider{ //.........其他的省略........ @Override public Uri insert(Uri uri, ContentValues values) { Log.i("Employeeprovider Info===================》》》》》","this is insert function"); // 获取数据库实例 SQLiteDatabase db = dbHelper.getWritableDatabase(); //dbHelper.onCreate(db); //创建表 // 插入数据,返回行ID Long rowID = db.insert(DBHelper.EMPLOYEES_TABLE_NAME, Employee.NAME, values); // 如果插入成功返回Uri if (rowID > 0) { Uri empUri = ContentUris .withAppendedId(Employee.CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(empUri, null); return empUri; } return null; } } 我在MainActivity中调用Insert方法时就报错,MainActivity中的onCreate方法中调用insert方法: [code="java"] public void insert() { //"content://com.hgl.test.employees/employee"; Uri uri = Employee.CONTENT_URI; // 实例化ContentValues ContentValues values = new ContentValues(); values.put(Employee.NAME, "android"); //values.put(Employee.GENDER, "software"); //values.put(Employee.AGE, 3); // 获取ContentResolver,并执行插入 getContentResolver().insert(uri, values); }[/code] 请问这是哪里的错误呢?

android sqlite数据库表字段更新

android sqlite数据库表字段更新,调用onUpgrade方法出现了Can't upgrade read-only database from version 3 to 4: 异常,有哪个大神碰到过或者知道怎么解决。 代码: public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = " alter table person modify phone varchar(100)"; db.execSQL(sql); } ``` ``` ``` ```

关于android APP开发中SQLITE数据库的问题

代码如下,首先请问我写的这段创建数据库的代码有没有错误?然后把这个类的文件放在哪里才对啊,目前程序一打开就是程序已经停止运行,APP的第一个ACTIVITY我设置的就是判断这个库中的某个表中有没有数据。我现在感觉就是程序打开,这个库还没有创建,是不存在的,所以运行不了。请大神指教下我。或者说怎么让APP一开始运行的第一步就是运行以下的代码来创建这个数据库。求指教。 //数据库创建类 package com.captain.dao; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class Db_create extends SQLiteOpenHelper { private static final int VERSION=1; //数据库版本号定义 private static final String DBN="manager.db"; public Db_create(Context context) { super(context,DBN,null,VERSION); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("create table tb_MoneyIn(_id integer primary key,user varchar(20)," + "money decimal,time varchar(10),type varchar(10),person varchar(100),mark varchar(200))"); db.execSQL("create table tb_MoneyOut(_id integer primary key,user varchar(20)," + "money decimal,time varchar(10),type varchar(10),person varchar(100),mark varchar(200))"); db.execSQL("create table tb_Users(_user integer primary key,pwd varchar(20))"); db.execSQL("create table tb_BianQian(_id integer primary key,user varchar(20)," + "content varchar(200))"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }

我想把SQLite数据库里的数据显示到ListView上,代码有什么问题吗?

private ListView listview = null; private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); private SimpleAdapter simpleAdapter = null; private ImageView iv; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //适配器添加查询结果,并加到ListView中显示 simpleAdapter = new SimpleAdapter(this, getData(), R.layout.item, new String[] {"name", "waimao","time","contact" ,"image"}, new int[] { R.id.name, R.id.waimao,R.id.time,R.id.contact,R.id.imageView1 }); listview.setAdapter(simpleAdapter); } /** * * @return */ private List<Map<String, Object>> getData() { DBHelper dbHelper = new DBHelper(this); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from post", null); while (cursor.moveToNext()) { Integer pid = cursor.getInt(cursor.getColumnIndex("id")); String pname = cursor.getString(cursor.getColumnIndex("name")); String waimao = cursor.getString(cursor.getColumnIndex("waimao")); String time=cursor.getString(cursor.getColumnIndex("time")); String contact=cursor.getString(cursor.getColumnIndex("contact")); //从数据库中提取图片 byte[] pimage=null; pimage=cursor.getBlob(cursor.getColumnIndex("image")); Bitmap imagebitmap=BitmapFactory.decodeByteArray(pimage, 0, pimage.length); iv=(ImageView)findViewById(R.id.imageView1); iv.setImageBitmap(imagebitmap); //这里同样是查询,只不过把查询到的数据添加到list集合,可以参照ListView的用法 Map<String, Object> map = new HashMap<String, Object>(); map.put("id", pid); //获取_id map.put("name", pname); //获取name map.put("waimao", waimao); map.put("time", time); map.put("contact", contact); map.put("image",imagebitmap); list.add(map); } return list; }

c# winform excel导入sqlite数据库,求代码

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Linq; using System.Windows.Forms; using DevExpress.XtraEditors; using System.Data.OleDb; using TenderClear.Common; using TenderClear.BLL.TC01; namespace TenderClear.UI.Forms.TC01 { public partial class TC010103Form : DevExpress.XtraEditors.XtraForm { public TC010103Form() { InitializeComponent(); } DataTable dt = new DataTable(); DataGridView dgv=new DataGridView(); private void txtExcel_Click(object sender, EventArgs e) { //打开excel选择框 OpenFileDialog frm = new OpenFileDialog(); frm.Filter = "Excel文件(*.xls,xlsx)|*.xls;*.xlsx"; if (frm.ShowDialog() == DialogResult.OK) { txtExcel.Text = frm.FileName; bind(txtExcel.Text); } } private void bind(string fileName) { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + "Extended Properties=Excel 8.0;"; OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn); DataSet ds = new DataSet(); try { da.Fill(ds); dt = ds.Tables[0]; this.dgv.DataSource = dt; } catch (Exception err) { MessageBox.Show("操作失败!" + err.ToString()); } } private void simpleButton2_Click(object sender, EventArgs e) { if (dgv.Rows.Count > 0) { DataRow dr = null; for (int i = 0; i < dt.Rows.Count; i++) { dr = dt.Rows[i]; insertToSql(dr); } MessageBox.Show("导入成功!"); } else { MessageBox.Show("没有数据!"); } } private void insertToSql(DataRow dr) { //excel表中的列名和数据库中的列名一定要对应 string xmlx = dr["XMLX"].ToString(); string xmbm = dr["XMXM"].ToString(); string xmmc = dr["XMMC"].ToString(); string xmdw = dr["XMDW"].ToString(); string dydj = dr["DYDJ"].ToString(); string zyxf = dr["ZYXF"].ToString(); string xmnr = dr["XMNR"].ToString(); DateTime kssj = Convert.ToDateTime(dr["KSSJ"].ToString()); DateTime jssj = Convert.ToDateTime(dr["JSSJ"].ToString()); int count=BLL10101.InsertOrUpdate(xmlx,xmbm,xmmc,xmdw,dydj,zyxf,xmnr,kssj,jssj); } } } 以上是我在网上找的代码,但是有出现错误,求大神们看看。![图片说明](https://img-ask.csdn.net/upload/201703/30/1490860056_295176.png)

QT 怎么样才能把Sqlite数据库表导出成txt或者csv?

static bool creatConnection() { //creat a database QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE","connection1"); db.setDatabaseName("my1.db"); db = QSqlDatabase::database("connection1"); //建立数据库连接 if(!db.open()){ QMessageBox::critical(0,"Cannot open database1", "Unable to establish a database connection.",QMessageBox::Cancel); return false; } QSqlQuery query1(db); query1.exec("create table shuju (Datetime QDateTime primary key,yanwu float,Temperature float,Humidity float)"); return true; } void SocketTCPServer::ReadDataFromSqlWriteToCSV(const QString &tableName,const QString &csvFileName)//将表导出为csv格式表格 { QSqlTableModel *exportModel = new QSqlTableModel(); exportModel->setTable(tableName); exportModel->select(); QStringList strList;//记录数据库中的一行报警数据 QString strString; const QString FILE_PATH(csvFileName); QFile csvFile(FILE_PATH); if (csvFile.open(QIODevice::ReadWrite)) { for (int i=0;i<exportModel->rowCount();i++) { for(int j=0;j<exportModel->columnCount();j++) { strList.insert(j,exportModel->data(exportModel->index(i,j)).toString());//把每一行的每一列数据读取到strList中 } strString = strList.join(", ")+"\n";//给两个列数据之前加“,”号,一行数据末尾加回车 strList.clear();//记录一行数据后清空,再记下一行数据 csvFile.write(strString.toUtf8());//使用方法:转换为Utf8格式后在windows下的excel打开是乱码,可先用notepad++打开并转码为unicode,再次用excel打开即可。 qDebug()<<strString.toUtf8(); } csvFile.close(); } } void SocketTCPServer::on_daochushuju_clicked() { ReadDataFromSqlWriteToCSV("shuju","shuju.csv"); }

SQLite读取全部数据

table中一共有11条记录,每个记录有三个内容"name","address","city"。现在要获取这些记录,但是我写的代码只能显示出一条记录,不知道怎么实现显示全部记录? public void readData(View v) { DatabaseClass mydb = new DatabaseClass(this); SQLiteDatabase readdata = mydb.getReadableDatabase(); TextView tv = (TextView)findViewById(R.id.readtext); Cursor c = readdata.rawQuery("select * from mylistdata", null); int[] elementId = {R.id.textView1, R.id.textView2, R.id.textView3}; if(c !=null) { c.moveToFirst(); while(c.isAfterLast() == false) { listData = new ArrayList<GenericListItem>(); String name = c.getString(c.getColumnIndex(DatabaseClass.NAME)); String address = c.getString(c.getColumnIndex(DatabaseClass.ADDRESS)); String city = c.getString(c.getColumnIndex(DatabaseClass.CITY)); listData.add(new GenericListItem(new String[]{name,address,city})); listAdapter = new GenericListAdapter(getApplicationContext(), R.layout.list_layout, listData, elementId); result.setAdapter(listAdapter); c.moveToNext(); } }

Android如何将SQLite数据库中的数据导出为csv格式的文件

搜到了下边这个方法,但是我没实现功能,请各位指教。最好能有代码 public void ExportToCSV(Cursor c, String fileName) { int rowCount = 0; int colCount = 0; FileWriter fw; BufferedWriter bfw; File sdCardDir = Environment.getExternalStorageDirectory(); File saveFile = new File(sdCardDir, fileName); try { rowCount = c.getCount(); colCount = c.getColumnCount(); fw = new FileWriter(saveFile); bfw = new BufferedWriter(fw); if (rowCount > 0) { c.moveToFirst(); // 写入表头 for (int i = 0; i < colCount; i++) { if (i != colCount - 1) bfw.write(c.getColumnName(i) + ','); else bfw.write(c.getColumnName(i)); } // 写好表头后换行 bfw.newLine(); // 写入数据 for (int i = 0; i < rowCount; i++) { c.moveToPosition(i); // Toast.makeText(mContext, "正在导出第"+(i+1)+"条", // Toast.LENGTH_SHORT).show(); Log.v("导出数据", "正在导出第" + (i + 1) + "条"); for (int j = 0; j < colCount; j++) { if (j != colCount - 1) bfw.write(c.getString(j) + ','); else bfw.write(c.getString(j)); } // 写好每条记录后换行 bfw.newLine(); } } // 将缓存数据写入文件 bfw.flush(); // 释放缓存 bfw.close(); // Toast.makeText(mContext, "导出完毕!", Toast.LENGTH_SHORT).show(); Log.d("导出数据", "导出完毕!"); Toast.makeText(SecondActivity.this, "默认Toast样式", Toast.LENGTH_SHORT).show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { c.close(); } }

创建数据库和默认数据

在SQlite数据库中插入默认数据 代码如下: private static final String DATABASE_CREATE_position = "CREATE TABLE position(latitude VARCHAR(20), longitude VARCHAR(20), address VARCHAR(100))"; @Override public void onCreate(SQLiteDatabase db) { // Create the table db.execSQL(DATABASE_CREATE_position); ContentValues defaultPos = new ContentValues(); defaultPos.put("latitude", "40.604398"); defaultPos.put("longitude", "-3.709002"); defaultPos.put("address", "Avenida del parque "); db.insert("position", null, defaultPos); db.close(); } 结果运行之后数据库是空的,请帮忙看一下问题出在哪里了?谢谢

用where条件查询SQLite数据库

在数据库中用string作为where条件查询数据库,程序就会关闭。如果换成数字作为条件,就没问题。帮我看一下代码: public ArrayList<Contact> getAvailableList() { // TODO Auto-generated method stub ArrayList<Contact> results = new ArrayList<Contact>(); String[] columns = new String[]{KEY_NAME, KEY_NUMBER, KEY_STATUS}; Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"=available" , null, null, null, KEY_NAME); String sName = ""; String sNum = ""; String status = ""; int iName = c.getColumnIndex(KEY_NAME); int iNumber = c.getColumnIndex(KEY_NUMBER); int iStatus = c.getColumnIndex(KEY_STATUS); Contact contact; for(c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()) { contact = new Contact(); sName += c.getString(iName); sNum += c.getString(iNumber); status += c.getString(iStatus); contact.setName(sName); //contact.setPhoneNumber(sNum); contact.setPhoneNumber("0".concat(sNum)); contact.setStatus(status); results.add(contact); sName = ""; sNum = ""; status = ""; } return results; }

关于sqlite3.24版本对数据库做更新操作被锁的问题

最近项目对sqlite版本做了更新,更新到了3.24,本来没有bug的项目现在出现了bug,本来的其中一个功能是要对项目的数据进行更新,需要同时更新多个数据,其中一个MAIN数据库需要其他的数据库都attach到这个数据库上,单线程下做更新时没有问题,但是双线程下更新时,更新到MAIN数据库时就会报错(此时其他数据库已经全班正常更新完成),错误是“database is busy”,请问有谁用过最新版的sqlite3吗?有没有碰到相同问题解决了的?

Android sqlite 计算一个int字段的总和,怎么在主页显示

SQLite数据库有个表叫account ,里面有一列的名字是balance,类型是int的。如何在dao里面写一个方法统计balance这一字段全部值的总和,并在mainactivity显示出来 图片是写在dao方法里面的,dao包里面包括了数据库的增删改功能 ![图片说明](https://img-ask.csdn.net/upload/201605/16/1463410593_619946.jpg)

保存SQLite android数据库中只有一行的id

<div class="post-text" itemprop="text"> <p>My android app is getting &amp; writing data to the server and to the SQlite database.</p> <p>I am fetching values for <code>jobaddress.id = 1</code>from server using a query (below). The values in <code>SELECT</code>statement are displaying perfectly in the UI of android app however when I press "Save", instead of values from the server, I need to save the id <code>1</code> from the server in the local database without shwoing the id in the UI. </p> <p>PHP sript (query only) for retrieving data from server:</p> <pre><code>$tsql = "SELECT tbl_manufacturers.manufacturers_name, tbl_appliances_models.appliances_models_name, tbl_appliances.appliances_serial, tbl_appliances.appliances_id, jobaddress.id FROM jobaddress INNER JOIN tbl_appliances ON jobaddress.id = tbl_appliances.appliances_jobaddress_id LEFT OUTER JOIN tbl_appliances_models INNER JOIN tbl_manufacturers ON tbl_appliances_models.appliances_models_manufacturers_id = tbl_manufacturers.manufacturers_id ON tbl_appliances.appliances_models_id = tbl_appliances_models.appliances_models_id WHERE (tbl_appliances.appliances_companies_id = 1) AND (jobaddress.id = 1)"; </code></pre> <p>Showing data using JSON Parser:</p> <pre><code>public void getJobAddress() { String result = null; InputStream isr = null; try { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://datanetbeta.multi-trade.co.uk/tablet/getJobAddress.php"); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); isr = entity.getContent(); } catch(Exception e) { Log.e("Log_tag", "Error in hhtp connection " + e.toString()); } //convert Response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) { sb.append(line + " "); } isr.close(); result = sb.toString(); } catch(Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONArray jArray = new JSONArray(result); for(int i=0; i &lt; jArray.length(); i++) { JSONObject json = jArray.getJSONObject(0); s = json.getString("address1"); t = json.getString("address2"); u = json.getString("postcode"); } tvJbAddrs1.setText(s); if(t == null) { tvJbAddrs2.setText(""); } else { tvJbAddrs2.setText(t); } tvJbPostcode.setText(u); } catch (Exception e) { Log.e("log_tag", "Error Parsing Data " + e.toString()); } } //getJobAddress() ends </code></pre> </div>

2019 Python开发者日-培训

2019 Python开发者日-培训

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

设计模式(JAVA语言实现)--20种设计模式附带源码

设计模式(JAVA语言实现)--20种设计模式附带源码

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

java后台+微信小程序 实现完整的点餐系统

java后台+微信小程序 实现完整的点餐系统

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

2019 AI开发者大会

2019 AI开发者大会

玩转Linux:常用命令实例指南

玩转Linux:常用命令实例指南

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Git 实用技巧

Git 实用技巧

Python数据清洗实战入门

Python数据清洗实战入门

使用TensorFlow+keras快速构建图像分类模型

使用TensorFlow+keras快速构建图像分类模型

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

程序员的算法通关课:知己知彼(第一季)

程序员的算法通关课:知己知彼(第一季)

MySQL数据库从入门到实战应用

MySQL数据库从入门到实战应用

机器学习初学者必会的案例精讲

机器学习初学者必会的案例精讲

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

.net core快速开发框架

.net core快速开发框架

玩转Python-Python3基础入门

玩转Python-Python3基础入门

Python数据挖掘简易入门

Python数据挖掘简易入门

微信公众平台开发入门

微信公众平台开发入门

程序员的兼职技能课

程序员的兼职技能课

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

HoloLens2开发入门教程

HoloLens2开发入门教程

微信小程序开发实战

微信小程序开发实战

Java8零基础入门视频教程

Java8零基础入门视频教程

相关热词 c# 解析cad c#数字格式化万 c#int转byte c#格式化日期 c# wpf 表格 c# 实现ad域验证登录 c#心跳包机制 c#使用fmod.dll c#dll vb 调用 c# outlook
立即提问
相关内容推荐