C#連接SQL Server



from https://dreamtails.pixnet.net/blog/post/28339210-%E5%88%9D%E5%AD%B8%E8%80%85%E5%85%A5%E9%96%80asp-.net-for-using-c%23-%E5%8F%96%E5%BE%97sql-server%E8%B3%87%E6%96%99

//test sql server connection
       string strConn = "server=.\\SQLExpress;database=databaseName;User ID=username;Password=password;Trusted_Connection=True;";
        //建立連接
        SqlConnection myConn = new SqlConnection(strConn);
        //打開連接
        myConn.Open();




from https://dotblogs.com.tw/chjackiekimo/2014/03/13/144377



        private void textBoxTID_TextChanged(object sender, EventArgs e)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(
                   new SqlConnectionStringBuilder()
                   {
                       DataSource = "19.16.17.15\\SQLEXPRESS",
                       InitialCatalog = "PAC,
                       UserID = "sa",
                       Password = "sa"
                   }.ConnectionString
                );

                conn.Open();

                String sql = "Select * from [dbo].[RECORD] "+
                    "whereTID= @TID "+
                    "order by  TIME desc";



                SqlCommand command = new SqlCommand(sql, conn);
                command.Parameters.AddWithValue("@TID", "0226");
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        if (reader["RESULT"].ToString().Equals("OK"))
                        {
                            labelPCBAResult.ForeColor = Color.Black;
                        }
                        else
                        {
                            labelPCBAResult.ForeColor = Color.Red;
                        }

                        labelPCBAResult.Text = String.Format("aaa:{0} {1}", reader["TIME"].ToString(), reader["RESULT"]);

                        // Console.WriteLine(String.Format("{0}", reader["RESULT"]));
                    }
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }

            finally
            {
                conn.Close();
            }
        }



Initial Catalog=[DB name]










//Insert
            SqlConnection connection = new SqlConnection(Constr);

                SqlCommand command = new SqlCommand();

                command.Connection = connection;            // <== lacking
                command.CommandType = CommandType.Text;
                command.CommandText =
    "INSERT into Spot_C " +
    "(Id,Name,Zone) " +
    "VALUES " +
    "(@Id,@Name,@Zone) ";
                command.Parameters.AddWithValue("@Id", info.Attributes["Id"].Value);
                command.Parameters.AddWithValue("@Name", info.Attributes["Name"].Value);
                command.Parameters.AddWithValue("@Zone", info.Attributes["Zone"].Value);

                try
                {
                    connection.Open();
                    int recordsAffected = command.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                    // error here
                }
                finally
                {
                    connection.Close();
                }


//select

            SqlConnection conn = null;

            try
            {
                conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
                conn.Open();
                SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);
                command.Parameters.AddWithValue("@zip", "india");
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while(reader.Read())
                    {
                        Console.WriteLine(String.Format("{0}", reader["id"]));
                    }
                } 
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
            }




















<CONFIG>
 <DB_Record DataSource="S04\SQLExpress"   DB_InitialCatalog = "QC"   UserID = "aa"   Password = "bb"   >
 </DB_Record>
</CONFIG>

         public string SingleReadXmlAttr(string m_XmlStruct, string m_Attr)
        {
            XmlDocument XmlDoc = new XmlDocument();
            string result = "";
            try
            {
                //XmlDoc.LoadXml(cv_XmlConfig);
                XmlDoc.Load(cv_ConfigPath);
                XPathNavigator nav = ((IXPathNavigable)XmlDoc).CreateNavigator();
                XPathNodeIterator iter = nav.Select(m_XmlStruct);
                iter.MoveNext();
                result = iter.Current.GetAttribute(m_Attr, "");
                iter = null;
                nav = null;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("SingleReadXmlAttr Error : " + ex.Message.ToString());
            }
            finally
            {
                XmlDoc = null;
            }
            return result;
        }
 

         SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();

             sb.DataSource = cv_CommonFunction.SingleReadXmlAttr("CONFIG/DB_Record", "DataSource");
            sb.InitialCatalog = cv_CommonFunction.SingleReadXmlAttr("CONFIG/DB_Record", "DB_InitialCatalog");
            sb.UserID = cv_CommonFunction.SingleReadXmlAttr("CONFIG/DB_Record", "UserID");
            sb.Password = cv_CommonFunction.SingleReadXmlAttr("CONFIG/DB_Record", "Password");

     SqlConnection conn = null;
            try
            {
                using (conn = new SqlConnection(sb.ConnectionString))
                {
                    conn.Open();
                    String sql = @"SELECT *   FROM  tableA where  id=@ id";
                    SqlCommand command = new SqlCommand(sql, conn);
                    command.Parameters.AddWithValue("id", id);

                    using (SqlDataReader reader = command.ExecuteReader())
                    { 
                            cell_id = reader["cell_id"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.Info(System.Reflection.MethodInfo.GetCurrentMethod().ToString() + "," + ex.Message.ToString());
                result = false;
            }             







留言

熱門文章