且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Android中使用SQLite数据库中创建表?

更新时间:2022-11-29 22:28:01

在第一个查询,你缺少一个右括号:

  CREATE TABLE IF NOT EXISTS编辑MyTAB(
    月INT(2),
    日期INT(2),
    年INT(4),
    事件VARCHAR;

它应该是:

  CREATE TABLE IF NOT EXISTS编辑MyTAB(
    月INT(2),
    日期INT(2),
    年INT(4),
    事件VARCHAR

另外,请注意查询并不需要以结束; ,如文档中提到:


  

参数结果
  的 SQL 的要执行的SQL语句。 用分号分隔的多个语句不被支持。


块引用>

此外,你应该始终检查LogCat中的输出,因为这应该抛出一个 SQLiteException


一些进一步的SQLite的注意事项:


  1. SQLite没有一个 VARCHAR 型。它只有 TEXT 并会转换任何文本样型进去。

  2. 请注意,给一个数据类型的长度也由SQLite的忽略:


  

SQLite的不强加任何长度限制(比其他大
  全球 SQLITE_MAX_LENGTH 限制)
对字符串,BLOB的长度或
  数值。


块引用>
public class MyAct extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SQLiteDatabase db = openOrCreateDatabase("MyDb",MODE_PRIVATE,null);
        db.execSQL("CREATE TABLE IF NOT EXISTS MyTab (Month INT(2),Date INT(2),Year INT(4),Event VARCHAR;");
        db.execSQL("INSERT INTO MyTab VALUES (0,1,2012,'mini_proj');");
        db.close();

    }
}

I have written this small snippet to create a table, but it's not working. What is the problem with this code?

In your first query, you are missing a closing brace:

CREATE TABLE IF NOT EXISTS MyTab (
    Month INT(2),
    Date INT(2),
    Year INT(4),
    Event VARCHAR;

It should be:

CREATE TABLE IF NOT EXISTS MyTab (
    Month INT(2),
    Date INT(2),
    Year INT(4),
    Event VARCHAR
)

Also, note that the query doesn't need to end with a ;, as mentioned in the docs:

Parameters
sql the SQL statement to be executed. Multiple statements separated by semicolons are not supported.

Also, you should ALWAYS check your LogCat output, since this should throw a SQLiteException.


Some further SQLite notes:

  1. SQLite doesn't have a VARCHAR-type. It only has TEXT and will convert any text-like type into it.
  2. Note that giving a length for a datatype is also ignored by SQLite:

SQLite does not impose any length restrictions (other than the large global SQLITE_MAX_LENGTH limit) on the length of strings, BLOBs or numeric values.