關於網路那些事...

網路行銷,SEO,網路趨勢,教學文章,網頁設計,生活時事

Winforms C# - Connect To Database Example

Winform Connect MSSQL

Setup Connection Info

Setup connection information in App.config like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <connectionStrings>
      <add name="SRVDBNAME" 
           providerName="System.Data.SqlClient"
           connectionString="server=DATABASENAME_STRING;uid=USERID_STRING;pwd=PASSWORD_STRING;database=TABLE_STRING;Max Pool Size=8000" />
    </connectionStrings>
</configuration>

Add Systemconfiguration to reference

Right click reference and add systemconfiguration

Connect and getData

First import namespace of fellowing:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Get configuration string and connect database

string cs = ConfigurationManager.ConnectionStrings["SRVDBNAME"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT TOP 1 * FROM tblTEST", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
    while (dr.Read())
    {
        test.Text =  dr["column1"].ToString()+","+dr["column2"].ToString() + "," + dr["column3"].ToString() + "," + dr["column4"].ToString() + "," + dr["column5"].ToString();
    }
}

如果你喜歡我們的文章內容,請在這裡按個讚



最新文章推薦