简体   繁体   English

我有一个来自 SQL Server 存储过程的 ArrayList,我想将所有数据插入 SQLite 数据库。 请看我下面的代码

[英]I have an ArrayList coming from SQL Server stored procedure and I want to insert all the data to a SQLite database. Please look at my code below

I was able to get data from SQL Server, but I don't know what to do after, Please help me or any idea how can I insert the data from my ArrayList to SQLite Database and insert it into a Custom ListView.我能够从 SQL Server 获取数据,但我不知道之后该怎么做,请帮助我或知道如何将 ArrayList 中的数据插入 SQLite 数据库并将其插入自定义 ListView。

................................................................................................. ..................................................... ..................................................

ConnectionHelper.java ConnectionHelper.java

package com.example.storedprocedures;

import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionHelper {
    Connection con;
    String ip = "***.***.*.***";
    String port = "*****";
    String classes = "net.sourceforge.jtds.jdbc.Driver";
    String database = "CentralizedDB";
    String username = "******";
    String password = "********";
    String url = "jdbc:jtds:sqlserver://"+ip+":"+port+"/"+database;

    @SuppressLint("NewApi")
    public Connection conclass(){
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection connection = null;
        try{
            Class.forName(classes);
            connection = DriverManager.getConnection(url, username, password);
        }catch(Exception exception){
            Log.e("Error:", exception.getMessage());
        }
        return connection;
    }
}

MainActivity.java MainActivity.java

package com.example.storedprocedures;

import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;


import android.os.Bundle;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    TextView lblheader;
    Button btnviewall,btnview;
    ListView lstTaggedList;
    EditText edtid;

    Connection connect;
    ResultSet rs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lblheader = (TextView) findViewById(R.id.lblheader);
        lstTaggedList = (ListView) findViewById(R.id.lstTaggedList);
        btnviewall = (Button) findViewById(R.id.btnviewall);
        btnview = (Button) findViewById(R.id.btnview);
        edtid = (EditText) findViewById(R.id.edtid);


        ConnectionHelper connectionHelper = new ConnectionHelper();
        connect = connectionHelper.conclass();
        btnviewall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {

                    PreparedStatement statement = connect.prepareStatement("EXEC SP_TaggedList");
                    final ArrayList list = new ArrayList();
                    rs = statement.executeQuery();
                    while (rs.next()) {
                        list.add(rs.getString("mrCode"));
                        list.add(rs.getString("docId_branch"));
                        list.add(rs.getString("brchName"));
                        list.add(rs.getString("industry_type"));
                        list.add(rs.getString("specialization_id"));
                        list.add(rs.getString("uName"));
                        list.add(rs.getString("class_id"));
                        list.add(rs.getString("max_visit"));
                    }
                    ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
                            android.R.layout.simple_list_item_1, list);
                    
                } catch (SQLException e) {
                    Toast.makeText(MainActivity.this, e.getMessage().toString(),
                            Toast.LENGTH_LONG).show();
                }
            }
        });

        btnview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {

                    PreparedStatement statement = connect.prepareStatement("EXEC SP_TaggedList '"+edtid.getText().toString()+"'");
                    final ArrayList list = new ArrayList();
                    rs = statement.executeQuery();
                    while (rs.next()) {
                        list.add(rs.getString("mrCode"));
                        list.add(rs.getString("docId_branch"));
                        list.add(rs.getString("brchName"));
                        list.add(rs.getString("industry_type"));
                        list.add(rs.getString("specialization_id"));
                        list.add(rs.getString("uName"));
                        list.add(rs.getString("class_id"));
                        list.add(rs.getString("max_visit"));
                    }
                    ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
                            android.R.layout.simple_list_item_1, list);



                } catch (SQLException e) {
                    Toast.makeText(MainActivity.this, e.getMessage().toString(),
                            Toast.LENGTH_LONG).show();
                }
            }
        });
        lstTaggedList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub

                String item = lstTaggedList.getItemAtPosition(position).toString();
                Toast.makeText(MainActivity.this, item + " selected", Toast.LENGTH_LONG).show();
            }
        });
    }
}

With SQLite on android, the typically way to use an SQLite database is to have a class that extends SQLiteOpenHelper .对于 Android 上的 SQLite,使用 SQLite 数据库的典型方法是拥有一个扩展SQLiteOpenHelper的类。

SQLiteOpenHelper will if the database does not exist call the onCreate method passing an empty SQLiteDatabase to the method (not totally empty as sqlite_master and android_metadata tables will exist, but empty as far as user tables will be concerned).如果数据库不存在, SQLiteOpenHelper将调用 onCreate 方法,将一个空的SQLiteDatabase传递给该方法(不完全为空,因为 sqlite_master 和 android_metadata 表将存在,但就用户表而言为空)。 You can then create the tables using the execSQL method for each table (or other components such as indexes, view triggers).然后,您可以使用 execSQL 方法为每个表(或其他组件,如索引、视图触发器)创建表。

You can also include other methods that cater for CRUD operations to access the data.您还可以包含其他满足 CRUD 操作的方法来访问数据。

Here's a Simple Demo of a database that drives a ListView.这是驱动 ListView 的数据库的简单演示

First DatabaseHelper ie the class that extends SQLiteOpenHelper :-第一个DatabaseHelper即扩展SQLiteOpenHelper的类:-

class DatabaseHelper extends SQLiteOpenHelper {

   public static final String DATABASE_NAME = "the_database.db";
   public static final int DATABASE_VERSION = 1;

   private static volatile DatabaseHelper INSTANCE; /* singleton instance of DatabaseHelper */
   private SQLiteDatabase db;

   /* Constructor (not publicly available) */
   private DatabaseHelper(Context context) {
      super(context,DATABASE_NAME,null,DATABASE_VERSION);
      db = this.getWritableDatabase();
   }

   /* Get singleton instance of DatabaseHelper */
   public static DatabaseHelper getInstance(Context context) {
      if (INSTANCE==null) {
         INSTANCE = new DatabaseHelper(context);
      }
      return INSTANCE;
   }

   public static final String TABLE_NAME = "the_table";
   public static final String COLUMN_MRCODE = BaseColumns._ID; /* Cursor Adapter must have _id column */
   public static final String COLUMN_DOCID_BRANCH = "docid_branch";
   public static final String COLUMN_BRCHNAME = "brchname";
   public static final String COLUMN_INDUSTRY_TYPE = "industry_type";
   public static final String COLUMN_SPECIALIZATION_ID = "specilization_id";
   public static final String COLUMN_UNAME = "uname";
   public static final String COLUMN_CLASS_ID = "class_id";
   public static final String COLUMN_MAX_VISIT = "max_visit";
   private static final String CRTSQL_THE_TABLE =
           "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
                   COLUMN_MRCODE + " INTEGER PRIMARY KEY" +
                   "," + COLUMN_DOCID_BRANCH + " INTEGER " +
                   "," + COLUMN_BRCHNAME + " TEXT " +
                   "," + COLUMN_INDUSTRY_TYPE + " TEXT " +
                   "," + COLUMN_SPECIALIZATION_ID + " INTEGER " +
                   "," + COLUMN_UNAME + " TEXT " +
                   "," + COLUMN_CLASS_ID + " INTEGER " +
                   "," + COLUMN_MAX_VISIT + " INTEGER " +
                   ")";
   private static final String CRTSQL_DOCID_BRANCH_INDEX =
           "CREATE INDEX IF NOT EXISTS " + COLUMN_DOCID_BRANCH + "_" + TABLE_NAME + "_idx001 " +
                   " ON " + TABLE_NAME + "(" +
                   COLUMN_DOCID_BRANCH +
                   ")";

   /* MUST be overridden (not much use if not used) */
   @Override
   public void onCreate(SQLiteDatabase db) {
      db.execSQL(CRTSQL_THE_TABLE);
      db.execSQL(CRTSQL_DOCID_BRANCH_INDEX);
   }

   /* MUST be overridden but doesn't necessarily have to do anything*/
   @Override
   public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

   }

   /* CRUD */

   public long insert(Long mrcode, long docid_branch, String brchname, String industry_type, String uname, long class_id, long max_visit ) {
      ContentValues cv = new ContentValues();
      if (mrcode != null) {
         cv.put(COLUMN_MRCODE,mrcode);
      }
      cv.put(COLUMN_DOCID_BRANCH,docid_branch);
      if (brchname != null) {
         cv.put(COLUMN_BRCHNAME,brchname);
      }
      if (industry_type != null) {
         cv.put(COLUMN_INDUSTRY_TYPE,industry_type);
      }
      if (uname != null) {
         cv.put(COLUMN_UNAME,uname);
      }
      cv.put(COLUMN_CLASS_ID,class_id);
      cv.put(COLUMN_MAX_VISIT,max_visit);
      return db.insert(TABLE_NAME,null,cv);
   }

   public Cursor getAllTheTableRows() {
      return db.query(TABLE_NAME,null,null,null,null,null,null);
   }
   @SuppressLint("Range")
   public long getNumberOfRowsInTheTable() {
      long rv=0;
      String output_column = "row_count";
      Cursor csr = db.query(TABLE_NAME,new String[]{"count(*) AS " + output_column},null,null,null,null,null);
      if (csr.moveToFirst()) {
         rv = csr.getLong(csr.getColumnIndex(output_column));
      }
      csr.close(); /* should always close cursors when done with them */
      return rv;
   }
}
  • as can be seen the database will可以看出,数据库将

    • have 1 table named the_table有 1 个名为the_table的表
    • have an index on the docid_branch column在 docid_branch 列上有一个索引
    • all the component names are defined based upon a single hard coded name.所有组件名称都是基于单个硬编码名称定义的。
  • have columns along the lines of what can be seen from your code.从您的代码中可以看到的内容列。

  • a singleton approach has been used使用了单例方法

  • some basic CRUD methods have been included to allow data to be inserted and extracted.包含一些基本的 CRUD 方法以允许插入和提取数据。

To demonstrate use of the DatabaseHelper and a means of driving a ListView (via a CursorAdapter) then MainActivity :-为了演示 DatabaseHelper 的使用和驱动 ListView 的方法(通过 CursorAdapter),然后是MainActivity :-

public class MainActivity extends AppCompatActivity {

    DatabaseHelper dbHelper;
    ListView lv;
    SimpleCursorAdapter sca;
    Cursor csr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbHelper = DatabaseHelper.getInstance(this);
        lv = this.findViewById(R.id.lv);
        if (dbHelper.getNumberOfRowsInTheTable() < 1) {
            addSomeTestData();
        }
        setOrRefreshListView();
    }

    /*
        Whenever the ListView is to be changed (including initially)
        this can be called.
     */
    private void setOrRefreshListView() {
        csr = dbHelper.getAllTheTableRows(); /* gets the latest data from the database */
        if (sca == null) {
            sca = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,
                    csr,
                    new String[]{DatabaseHelper.COLUMN_UNAME,DatabaseHelper.COLUMN_INDUSTRY_TYPE}, /* The column names in the Cursor */
                    new int[]{android.R.id.text1,android.R.id.text2},0); /* The respective id's in the ListView's layout */
            lv.setAdapter(sca);
        } else {
            sca.swapCursor(csr);
        }
    }

    private void addSomeTestData() {
        dbHelper.insert(001L,111,"Branch001","MINING","FRED",1,10);
        dbHelper.insert(null,222,"Branch002","HOSPITALITY","MARY",6,1);
        dbHelper.insert(null,333,"Branch003","REFINING","JANE",5,5);
    }
}
  • Note that for brevity a predefined/stock layout has been used请注意,为简洁起见,已使用预定义/库存布局

Results结果

When run then :-运行时:-

在此处输入图像描述

Using App Inspection then :-然后使用应用检查:-

在此处输入图像描述

  • as can bee seen the specialization_id is NULL this is because the insert method in the DatabaseHelper class omitted consideration of the column.可以看出,specialization_id 为 NULL,这是因为DatabaseHelper类中的insert方法省略了对列的考虑。

Again using App Inspection but with a custom query then :-再次使用应用检查,但使用自定义查询:-

在此处输入图像描述

  • android_metadata table can be seen to exist (contains the locale and is android specific)可以看到 android_metadata 表存在(包含语言环境并且是 android 特定的)
  • the docid_branch_the_table_idx001 index has been created. docid_branch_the_table_idx001索引已创建。

how can I insert the data from my ArrayList to SQLite Database如何将 ArrayList 中的数据插入 SQLite 数据库

So with the above you just need to get an Instance of the the DatabaseHelper and then invoke the insert method whilst looping through your ArrayList.因此,使用上述方法,您只需要获取 DatabaseHelper 的实例,然后在循环遍历 ArrayList 时调用 insert 方法。

  • This isn't the best solution as each insert is done in it's own transaction.这不是最好的解决方案,因为每个插入都是在它自己的事务中完成的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我想使用Java连接到SQL Server,请找到下面的代码,并且出现“错误消息”下方给出的异常 - i want to connect to SQL Server using Java, please find the code below and i am getting the exception as given below “Error Message” 我的代码仅从数据库的第一个字段检索数据。 请查看详细信息 - My code is retrieving data only from first field of my database. Please see details 如何在SQL中使用存储过程从所有表中获取所有记录 - How can i get all records from all tables using stored procedure in my sql 我想使用ArrayList从数据库中显示控制台中的所有数据 - I want to display all the data in my console from the data base using ArrayList 我已经从sqlite数据库中填充了自定义列表视图。 列表视图自定义行包含一个imageview,textview和button。 - I have populated my custom list view from sqlite database. List view custom row contains one imageview ,textview and button. 我在 Oracle 数据库中有一个 SQL 存储过程,参数为时间戳。 如何调用程序 - I have a SQL Stored procedure in Oracle database with parameter as timestamp. How to call the procedure 如何在 mysql 中创建存储过程并在 JAVA 中调用它。 我需要一些帮助来创建一个可调用的过程。 下面是我的代码 - How to create stored procedure in mysql and call it in JAVA. i need some help on creating a callable procedure. below id my code Java中的$符号是什么? 请查看下面的Java代码 - What is the $ sign in Java? Please have a look in the Java code below 我的JSP页面不是从数据库中获取数据。 我该怎么做才能改善这个? - My JSP page is not fatching data from database. What should I do to Improve this? 我需要显示一些我保存在房间数据库中的数据。 我忘记添加到代码中或缺少什么? - I need to show some data that I saved in my room database. What did I forget to add to code or what is it missing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM