使用mssql数据库中的值创建对象

时间:2017-05-18 12:09:22

标签: c# sql-server

我有一个包含以下表格的数据库:

**Camping Spot**
PK - id          - int
FK - location_id - int
     number      - int
     capacity    - int

**Location**
PK - id          - int
     name        - string
     street      - varchar
     etc.

**Event**
PK - id          - int
FK - location_id - int
     name        - string
     datestart   - datetime
     etc.

我有以下课程

namespace modellen
{
    public class Spot
    {
        public int Id { get; set; }
        public int Number { get; set; }
        public int Capacity { get; set; }
    }
}

namespace DAL_laag
{
    public class SpotDal
    {
        List<Spot> spots = new List<Spot>();
        private Database database = new Database();

        public GiveAvailiableSpots(int event_id)
        {
            string query = "A query that gets Id, Number and Capacity";
            return ?
        }

    }

我想通过mssql查询从表中获取id,number和capacity值。然后我想创建一个新的Spot对象并将该对象添加到我的Spots列表中。

我无法弄清楚获取这三个值的查询是什么以及使用这三个值创建新对象的代码。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

我认为您的查询需要看起来像这样。

Attore::create

你对db的调用看起来像这样:

string query = @"select  id, 
        number, 
        capacity 
from tblCampingSport cs
left join tblLocation l on cs.location_id == l.id
left join tblEvent e on e.location_id = l.id
where e.id = @eventId";

您的课程要存储结果:

List<QueryResult> results = new List<QueryResult>();

using(SqlConnection conn = new SqlConnection(ConnectionString))
{
    conn.Open();
    using(SqlCommand cmd = new SqlCommand(query, conn)
    {
        cmd.Parameters.AddWithValue("@eventId", event_id);
        var reader = cmd.ExecuteReader();

        if(reader.HasRows())
        {
            while(reader.Read())
            {
                QueryResult result = new QueryResult();
                result.EventId = (int)reader["id"];
                result.Number = (int)reader["number"];
                result.Capacity = (int)reader["capacity"];
                results.Add(result);
            }
        }
    }
}

这些都没有经过测试甚至编译(直接写入此文本框),但我认为这是如何从表中获得所需内容的大致轮廓。

答案 1 :(得分:0)

假设您正在使用MySql Libary连接到您的数据库。您需要一个允许您连接到数据库的类,该数据库看起来像下面的代码段;我正在使用带有c#的UWP for Windows 10,所以代码应该可以工作,但是,可能会有轻微的变化,但没什么大的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using Windows.UI.Popups;
using Walsall_College_Auditor.Classes;

namespace Walsall_College_Auditor.Models
{
class dbConnect
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string uid;
    private string password;

    //Constructor
    public dbConnect()
    {
        Initialize();
    }

    //Initialize values
    private void Initialize()
    {
        //Prevent the application from throwing "windows-1252' is not a supported encoding name."
        System.Text.EncodingProvider ppp;
        ppp = System.Text.CodePagesEncodingProvider.Instance;
        Encoding.RegisterProvider(ppp);

        server = "localhost";
        database = "your_db_name"; //Put the new database name here
        uid = "root"; //Your db Login/Username
        password = ""; //Your db login password
        string connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" 
            + "UID=" + uid + ";" + "PASSWORD=" + password + ";SslMode=None";

        connection = new MySqlConnection(connectionString);
    }

    //open connection to database
    private bool OpenConnection()
    {
        try
        {
            connection.Open();
            return true;
        }
        catch (MySqlException ex)
        {
            //When handling errors, you can your application's response based 
            //on the error number.
            //The two most common error numbers when connecting are as follows:
            //0: Cannot connect to the server.
            //1045: Invalid username and/or password.
            switch (ex.Number)
            { 
                case 0:
                    var dialog1 = new MessageDialog("Cannot connect to server.  Contact administrator");
                    dialog1.Title = "Connection Error";
                    dialog1.ShowAsync();
                    break;

                case 1045:
                    var dialog2 = new MessageDialog("Invalid username/password, please try again");
                    dialog2.Title = "Connection Error";
                    dialog2.ShowAsync();
                    break;
            }
            return false;
        }
    }

    //Close connection
    private bool CloseConnection()
    {
        try
        {
            connection.Close();
            return true;
        }
        catch (MySqlException ex)
        {
            var dialog = new MessageDialog(ex.Message);
            dialog.Title = "Disconnecting Error";
            dialog.ShowAsync();
            return false;
        }
    }

如果您需要,我还可以发布其他方法。就个人而言,我使用这个Connect c# to MySql来帮助我开发查询数据库的方法。如果您使用的是Windows窗体,那么这将是完美的,如果您使用的是通用Windows平台,那么您将需要一个不同版本的DLL文件,并对您提供的链接上未显示的代码进行调整。

但是要正确回答您的问题:下面的代码存在于同一个DB类中,代码是一个返回公司列表的函数。

public List<company> getSots()
    {
        string query = "SELECT * FROM tbl_spot"; //Your table name here
        List<Spot> dbSpots = new List<Spot>(); //List to store the gathered spots
        if (this.OpenConnection() == true)
        {
            MySqlCommand cmd = new MySqlCommand(query, connection);
            MySqlDataReader dataReader = cmd.ExecuteReader();
            while (dataReader.Read())
            {
                //Create a new company object and populate with a row at a time
                Spot x = new Spot();
                x.Id = int.Parse(dataReader["id_spot"].ToString());
                x.Number = int.Parse(dataReader["number"].ToString());
                x.Capacity = int.Parse(dataReader["capacity"].ToString());
                dbSpots.Add(x); //Add created Spot to the Spots list
            }
            dataReader.Close();
            this.CloseConnection();
            return dbCmpys; //Return the gathered db companies
        }
        else { return dbCmpys; }
    }

正如您所看到的,代码创建了一个对象类型列表(在您的情况下为Spot),使用循环填充它以循环遍历所有数据库记录并在完成后返回列表。

使用该函数:在另一个类或表单中,创建一个新的DB类实例,创建一个等于该函数的列表;像这样:

//Your form code/class
class SpotForm
{
    private dbConnect dbConnection = new dbConnect(); //Database connection
    private List<Spot> listSpots = new List<Spot>(); //Local list

    // Constructor
    public SpotForm()
    {
        listSpots = dbConnection.getSpots();
    }

现在,您将拥有数据库中的Spots列表,可以根据需要进行循环,以收集或操作数据。