База данных с 5 таблицами со вставкой и выбором - PullRequest
0 голосов
/ 06 января 2011

Моя проблема в том, что у меня есть 5 таблиц, и мне нужно вставить и выбрать.

я сделал для каждой таблицы класс, и там я написал SQL-операторы вот так

    public class Contact

private static String IDCont = "id_contact";
    private static String NameCont = "name_contact";
    private static String StreetCont = "street_contact";
    private static String Street2Cont = "street2_contact";
    private static String Street3Cont = "street3_contact";
    private static String ZipCont = "zip_contact";
    private static String CityCont = "city_contact";
    private static String CountryCont = "country_contact";
    private static String Iso2Cont = "iso2_contact";
    private static String PhoneCont = "phone_contact";
    private static String Phone2Cont = "phone2_contact";
    private static String FaxCont = "fax_contact";
    private static String MailCont = "mail_contact";
    private static String Mail2Cont = "mail2_contact";
    private static String InternetCont = "internet_contact";
    private static String DrivemapCont = "drivemap_contact";
    private static String PictureCont = "picture_contact";
    private static String LatitudeCont = "latitude_contact";
    private static String LongitudeCont = "longitude_contact";
    public static final String TABLE_NAME = "contact";
        public static final String SQL_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
        IDCont + "INTEGER not NULL," +
        NameCont + " TEXT not NULL," +
        StreetCont + " TEXT," +
        Street2Cont + " TEXT," +
        Street3Cont + " TEXT," +
        ZipCont + " TEXT," +
        CityCont + " TEXT," +
        CountryCont + " TEXT," +
        Iso2Cont + " TEXT," +
        PhoneCont + " TEXT," +
        Phone2Cont + " TEXT," +
        FaxCont + " TEXT," +                
        MailCont + " TEXT," +
        Mail2Cont + " TEXT," +
        InternetCont + " TEXT," +       //website of the contact
        DrivemapCont + " TEXT," +       //a link to a drivemap to the contact
        PictureCont + " TEXT," +            //a photo of the contact building (contact is not a person)
        LatitudeCont + " TEXT," +
        LongitudeCont + " TEXT," +
        "primary key(id_contact)" +
        "foreign key(iso2)";

and my insert looks like this

    public boolean SQL_INSERT_CONTACT(int IDContIns, String NameContIns, String StreetContIns,
                    String Street2ContIns, String Street3ContIns, String ZipContIns, 
                    String CityContIns, String CountryContIns, String Iso2ContIns,
                    String PhoneContIns, String Phone2ContIns, String FaxContIns,
                    String MailContIns, String Mail2ContIns, String InternetContIns,
                    String DrivemapContIns, String PictureContIns, String LatitudeContIns,
                    String LongitudeContIns) {
        try{
        db.execSQL("INSERT INTO " + "contact" +
                "(" + IDCont + ", " + NameCont + ", " + StreetCont + ", " + 
                Street2Cont + ", " + Street3Cont + ", " + ZipCont + ", " + 
                CityCont + ", " + CountryCont + ", " + Iso2Cont + ", " + 
                PhoneCont + ", " + Phone2Cont + ", " + FaxCont + ", " + 
                MailCont + ", " + Mail2Cont + ", " + InternetCont + ", " + 
                DrivemapCont + ", " + PictureCont + ", " + LatitudeCont + ", " + 
                LongitudeCont + ") " +
                "VALUES (" + IDContIns + ", " + NameContIns +", " + StreetContIns + ", " +
                Street2ContIns + ", " + Street3ContIns + ", " + ZipContIns + ", " +
                CityContIns + ", " + CountryContIns + ", " + Iso2ContIns + ", " + 
                PhoneContIns + ", " + Phone2ContIns + ", " + FaxContIns + ", " + 
                MailContIns + ", " + Mail2ContIns + ", " + InternetContIns + ", " + 
                DrivemapContIns + ", " + PictureContIns + ", " + LatitudeContIns + ", " + 
                LongitudeContIns +")");
        return true;
        }
        catch (SQLException e) {
            return false;   
        }

    }

У меня там есть класс DBAdapter, я создал базу данных

 public class DBAdapter {

         public static final String DB_NAME = "mol.db";
            private static final int DB_VERSION = 1;
            private static final String TAG = "DBAdapter";      //to log

            private final Context context;
            private SQLiteDatabase db;

        public DBAdapter(Context context) 
            {
                this.context = context;
                OpenHelper openHelper = new OpenHelper(this.context);
                this.db = openHelper.getWritableDatabase();
        }

     public static class OpenHelper extends SQLiteOpenHelper 
        {

            public OpenHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }
    @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL(Contact.SQL_CREATE);
            db.execSQL(Country.SQL_CREATE);
            db.execSQL(Picture.SQL_CREATE);
            db.execSQL(Product.SQL_CREATE);
            db.execSQL(Project.SQL_CREATE);

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w(TAG, "Upgrading database from version "
                    + oldVersion + " to " + newVersion
                    + ", which will destroy all old data");
            db.execSQL(Contact.SQL_DROP);
            db.execSQL(Country.SQL_DROP);
            db.execSQL(Picture.SQL_DROP);
            db.execSQL(Product.SQL_DROP);
            db.execSQL(Project.SQL_DROP);
            onCreate(db);
        }

Я нашел много разных вещей и попробовал их, но у меня ничего не получалось ... мне нужно знать, как я могу получить доступ к базе данных в моей деятельности и как я могу заставить вставку работать и есть ли что-то не так в моем коде? спасибо за вашу помощь

вот как я пытался включить это в свою деятельность

public class MainTabActivity extends TabActivity {


private Context context;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.maintabactivity);

    TabHost mTabHost = getTabHost();



    Intent intent1 = new Intent().setClass(this,MapOfLight.class);
    //Intent intent2 = new Intent().setClass(this,Test.class);              //Testactivity
    //Intent intent2 = new Intent().setClass(this,DetailView.class);        //DetailView
    Intent intent2 = new Intent().setClass(this,ObjectList.class);      //ObjectList
    //Intent intent2 = new Intent().setClass(this,Gallery.class);           //Gallery
    Intent intent3 = new Intent().setClass(this,ContactDetail.class);
    mTabHost.addTab(mTabHost.newTabSpec("tab_mol").setIndicator(this.getText(R.string.mol), getResources().getDrawable(R.drawable.ic_tab_mol)).setContent(intent1));
    mTabHost.addTab(mTabHost.newTabSpec("tab_highlights").setIndicator(this.getText(R.string.highlights),getResources().getDrawable(R.drawable.ic_tab_highlights)).setContent(intent2));
    mTabHost.addTab(mTabHost.newTabSpec("tab_contacts").setIndicator(this.getText(R.string.contact),getResources().getDrawable(R.drawable.ic_tab_contact)).setContent(intent3));

    mTabHost.setCurrentTab(1);



    SQLiteDatabase db;
    DBAdapter dh = null;
    OpenHelper openHelper = new OpenHelper(this.context);


    dh = new DBAdapter(this);
    db = openHelper.getWritableDatabase();

    dh.SQL_INSERT_COUNTRY("AT", "Austria", "AUT");

}

}

Я попробовал это с моей таблицей стран, потому что она имеет только 3 столбца

public class Country {

    private static String Iso2Count = "iso2_country";
    private static String NameCount = "name_country";
    private static String FlagCount = "flag_image_url_country";

    public static final String TABLE_NAME = "country";
    public static final String SQL_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
    Iso2Count + " TEXT not NULL," +
    NameCount + " TEXT not NULL," +
    FlagCount + " TEXT not NULL," +
    "primary key(iso2_country)";

    public boolean SQL_INSERT_COUNTRY(String Iso2CountIns, String NameCountIns, String FlagCountIns) {
        try{
        db.execSQL("INSERT INTO " + "country" +
                "(" + Iso2Count + ", " + NameCount + ", " + FlagCount + ") " +
                "VALUES ( " + Iso2CountIns + ", " + NameCountIns +", " + FlagCountIns + " )");
        return true;
        }
        catch (SQLException e) {
            return false;   
        }

    }

еще один вопрос: лучше ли поместить вставку и выбрать из каждой таблицы в отдельный класс, поэтому у меня есть 1 класс для каждой таблицы или все они помещены в класс DBAdapter?

1 Ответ

0 голосов
/ 06 января 2011

РЕДАКТИРОВАТЬ: Я не уверен, что вы показали весь свой код, и поэтому я не уверен, что мой ответ полезен. Где вы объявляете переменные IDCont, NameCont, StreetCont ...? Я предполагаю, что они являются константами, определяющими имена ваших полей. В этом случае мой ответ неверен, так как он должен сформировать правильное утверждение INSERT.

Можете ли вы добавить сообщения об ошибках, которые вы видите, а также более конкретную информацию о сервере БД, который вы используете?


Ваш оператор INSERT не будет работать, потому что вы вставляете значения переменных, переданных в функцию, вместо указания имен столбцов.

В первой части устава должна быть вся одна строка:

"INSERT INTO contact (IDCont, NameCont, StreetCont, Street2Cont, Street3Cont, ZipCont," + 
    "CityCont, CountryCont, Iso2Cont, PhoneCont, Phone2Cont, FaxCont, MailCont, " +
    "Mail2Cont, InternetCont, DrivemapCont, PictureCont, LatitudeCont, LongitudeCont) " 
"VALUES ("IDContIns + ", " + NameContIns +", " + StreetContIns + ", " +
            Street2ContIns + ", " + Street3ContIns + ", " + ZipContIns + ", " +
            CityContIns + ", " + CountryContIns + ", " + Iso2ContIns + ", " + 
            PhoneContIns + ", " + Phone2ContIns + ", " + FaxContIns + ", " + 
            MailContIns + ", " + Mail2ContIns + ", " + InternetContIns + ", " + 
            DrivemapContIns + ", " + PictureContIns + ", " + LatitudeContIns + ", " + 
            LongitudeContIns +")"

Я также хотел бы задать вопрос о вашей таблице, почему большинство полей TEXT, а не более подходящий тип данных?

...