C#/ Sqlite将查询结果存储为变量的简单方法

时间:2012-09-14 09:05:01

标签: c# sql sqlite function

我是C#的半新手,但特别是在C#中使用Sqlite,目前我有一个SQlite数据库设置很好,它与应用程序的连接很好我运行Windows窗体应用程序,我已绑定数据库中的表到数据网格视图。

这很好我有一个函数设置来运行查询,我将SQL语句作为字符串传递给函数,并将其作为查询运行。

我正在徘徊我如何从查询中得到一个结果我明知道它会像是

private string QueryResult(string query){
    connect
    run query
    read query 
    return result
}

我见过的所有例子都使用Sqlreader,但我似乎无法使它工作,我真的习惯使用PHP和SQL,这比在C#中使用它更简单可以有人解释或指出某处我或许可以找到一个tutuorial或函数,你可以通过将它作为一个字符串传递来运行任何查询,并简单地返回结果?我需要的结果不会是数组或巨大的东西,我只想一次返回1个字符串或数字,所以我不需要任何复杂的东西。

请帮帮我,我昨晚花了大约4个小时阅读这些东西并且似乎没有到达任何地方。

4 个答案:

答案 0 :(得分:9)

试试这个,也许它会对你有所帮助:

public string QueryResult(string query)
{
    string result = "";
    SQLiteConnection sqlite = new SQLiteConnection("Data Source=/path/to/file.db");
    try
    {
        sqlite.Open();  //Initiate connection to the db
        SQLiteCommand cmd = sqlite.CreateCommand();
        cmd.CommandText = query;  //set the passed query
        result = cmd.ExecuteScalar().ToString();
    }
    finally
    {
        sqlite.Close();
    }
    return result;
}

答案 1 :(得分:3)

这是我用过的方法......

首先,构建一个类来表示数据库中的表: -

public class Contact
    {
        public int ContactID { get; set; }
        public string Surname { get; set; }
        public string Forename { get; set; }
        public string MobileNumber { get; set; }
        public string EmailAddress { get; set; }
        public string Information { get; set; }   
    }

然后我将此数据加载到IEnumerable列表中: -

public List<Contact> GetContacts()
        {
            DataTable dt = new DataTable();

            OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Contacts]", Connection);
            Adapter.SelectCommand = cmd;

            Connection.Open();
            Adapter.SelectCommand.ExecuteNonQuery();
            Adapter.Fill(dt);
            Connection.Close();

            var Contacts = (from row in dt.AsEnumerable()

                            select new Contact
                            {
                                ContactID = row.Field<int>("ContactID"),
                                Surname = row.Field<string>("Surname"),
                                Forename = row.Field<string>("Forename"),
                                MobileNumber = row.Field<string>("MobileNumber"),
                                EmailAddress = row.Field<string>("EmailAddress"),
                                Information = row.Field<string>("Information")

                            }).ToList();



            return Contacts;
        }

在我的应用程序中,我创建了一个此对象的实例: -

   public List<Contact> contactData;
   contactData = dc.GetContacts();

我现在有权使用LINQ操作数据: -

var Query = ConactData.Where(item=> item.ContactID == 10)
            .Select(item=> item.Surname).toString(); 

您可以使用LINQ查询您的数据并将其存储为Lists,Strings等等。

希望这有助于。

答案 2 :(得分:1)

//在正常逻辑中

SELECT (SELECT SUM(column_name) FROM table_name WHERE condition) - (SELECT SUM(column_name) FROM table_name WHERE condition)

//实际编码示例

public void total_due()
                {
                    string query = "select (select sum(amount) from table_name where id>0 and amount>paid and [order no] like '" + textbox1.Text + "%' and [name] like '" + textbox2.Text + "%' and [date] like '" + textbox3.Text + "%' ) - (select sum(paid) from table_name where id>0 and amount>paid and [order no] like '" + textbox1.Text + "%' and [name] like '" + textbox2.Text + "%' and [date] like '" + textbox3.Text + "%' )";
                    SqlConnection con = new SqlConnection("server=server_name;Database=database_name;UID=sa;Password=password;");
                    con.Open();
                    SqlCommand cmd = new SqlCommand(query,con);
                    due.Text = cmd.ExecuteScalar().ToString();
                    con.Close();
                }

答案 3 :(得分:0)

通常,我会这样做:

string CONNECTION_STRING = "Persist Security Info=False; Integrated Security = SSPI; Initial Catalog=DATABASENAME;Data Source=SERVERIP";

string query = "IF OBJECT_ID('TABLE_NAME') IS NOT NULL SELECT * FROM TABLE_NAME";

using (SqlConnection Connection = new SqlConnection(CONNECTION_STRING))
{
    using (SqlCommand sqlCommand = new SqlCommand(query, ConnectionString))
    {
        try
        {
            Connection.Open();
            SqlDataReader queryCommandReader = sqlCommand.ExecuteReader();
            DataTable dataTable = new DataTable();
            dataTable.Load(queryCommandReader);

            if (dataTable != null)
            {
                 if (dataTable.Rows != null)
                 {
                     if (dataTable.Rows.Count > 0)
                     {
                         String rowText = "";
                         rowText += dataTable.Rows[ROW_NUM] [COLUMN_NAME];                          
                     }
                 }
            }
        }
        catch (Exception)
        {
            ...
        }
        finally
        {
               ...
        }