首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C#调用存储过程。要代码,该如何处理

2013-12-19 
C#调用存储过程。要代码using Systemusing System.Collections.Genericusing System.ComponentModelusin

C#调用存储过程。要代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Collections;
using System.Threading;
using System.Timers;
using System.Xml;
using System.Runtime.InteropServices;
using System.Data.SqlClient;
using System.Configuration;

namespace 串口通信
{
    public partial class Form1 : Form
    {
        public bool isFirstTimeToStart = true;
        private int timeStamp = 50;

        public Form1()
        {   
            InitializeComponent();   
        }
        /// <summary>
        /// 初始化串口属性
        /// </summary>
        public void InitializeSerialPort()
        {
            if (isFirstTimeToStart == true)
            {
                port.DataBits = 8;
                port.PortName = ConfigurationManager.AppSettings["port"].ToString();
                port.BaudRate = 19200;
                port.DiscardNull = false;
                port.DtrEnable = false;
                port.Handshake = Handshake.None;
                port.Parity = Parity.None;
                port.ParityReplace = Convert.ToByte("63");
                port.RtsEnable = false;
                port.StopBits = StopBits.One;
                isFirstTimeToStart = false;
            }
        }

        private void comboBox1_DropDown(object sender, EventArgs e)
        {
            ///加载计算机上所有的COM串口
            comboBox1.Items.Clear();
            string[] ports = SerialPort.GetPortNames();
            foreach (string p in ports)
            {
                comboBox1.Items.Add(p);
            }
        }

        //打开串口
        private void button1_Click(object sender, EventArgs e)
        {
            InitializeSerialPort();
            port.Open();
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
        }

        //执行串口方法
        void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            ArrayList array = new ArrayList();
            READAGAIN:
                while (port.BytesToRead > 0)
                {
                    array.Add((byte)port.ReadByte());


                }
                Thread.Sleep(timeStamp);
                if (port.BytesToRead > 0)
                {
                    goto READAGAIN;
                }
                InitializedListView2(array);
        }
        delegate void SetInfo(ArrayList infos);


        public void InitializedListView2(ArrayList arrayList)
        {
            try
            {
                if (this.label2.InvokeRequired)
                {
                    SetInfo ss = new SetInfo(InitializedListView2);
                    this.Invoke(ss, new object[] { arrayList });
                }
                else
                {
                    byte[] data = new byte[arrayList.Count + 1];
                    string str = "";
                    for (int i = 0; i < arrayList.Count; i++)
                    {
                        data[i] = (byte)(arrayList[i]);
                        string aa = data[i].ToString("X");
                        str += (data[i].ToString("X").Length == 2 ? data[i].ToString("X") : "0" + data[i].ToString("X")) + " ";
                    }
                    if (str.Trim().Equals("00 1E 98"))

                    {
                        label2.Text = "离开红外感应!";
                    }
                    else if (str.Trim().Equals("00 1E 9E"))
                    {
                        label2.Text = "进入红外感应!";
                        MessageBox.Show("警告", "确认", MessageBoxButtons.OKCancel,MessageBoxIcon.Warning);
                        int sleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["sleepTime"]);
                        Thread.Sleep(sleepTime);
                    }
                    else
                    {
                        label2.Text = "错误!";


                    }
                    textBox1.Text += str + "\r\n";
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        protected void DataReceived(string info)
        {
           // rtbSerialInfo.Text += (SignalToHexCode(info).ToUpper()) + "\r\n";
            switch (info)
            {
                case "00 1E 98":
                    label2.Text = "离开红外感应!";
                    break;
                case "00 1E 9E":
                    label2.Text = "进入红外感应!";
                    break;
                default:
                    label2.Text = "错误!";
                    break;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string con = ConfigurationManager.AppSettings["Sqlconn"].ToString();
            port.PortName = ConfigurationManager.AppSettings["port"].ToString();
            SqlConnection conn = new SqlConnection(con);
            conn.Open();
            SqlDataReader returnReader;
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.StoredProcedure;        //设置cmd的类型为存储过程
            returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.CommandText = "EXEC usp_CallSceneStep";       //存储过程名
            cmd.Connection = conn;

            //SqlParameter pCustomerID = new SqlParameter();
            //pCustomerID.ParameterName = "@CustomerID";
            //pCustomerID.SqlDbType = SqlDbType.NChar;
            //pCustomerID.Value = "ALFKI";
            //cmd.Parameters.Add(pCustomerID);
          


            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
            }
        }
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        }

        //鼠标双击图标,显示界面
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.TopMost = true;
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)  //关闭按钮事件
        {
            e.Cancel = true;
            this.Hide();
        }

        //最小化到托盘
        private void Form1_SizeChanged(object sender, EventArgs e)     //最小化事件按钮
        {
            this.Hide();
        }

        //托盘右键显示
        private void hideMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        //托盘右键隐藏
        private void showMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        //托盘右键退出
        private void exitMenuItem_Click_1(object sender, EventArgs e)
        {
            if (MessageBox.Show("你确定要退出终端服务程序吗?", "确认", MessageBoxButtons.OKCancel,
                MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                notifyIcon1.Visible = false;
                this.Close();
                this.Dispose();
                Application.Exit();
            }      
        }
    }   
}



需求要写一个存储过程,
存储过程名称为:EXEC usp_CallSceneStep,

数据库链接我是用App.config实现的。 
如何去调用?要代码。
------解决方案--------------------


调用方法
http://blog.csdn.net/newd_2011/article/details/7766981
[解决办法]
SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.StoredProcedure;        //设置cmd的类型为存储过程
            cmd.CommandText = "EXEC usp_CallSceneStep";       //存储过程名
            cmd.Connection = conn;
cmd.executenoquery();
你调用这个方法就OK,方法名拼写可能有错误。
[解决办法]
cmd.CommandType = CommandType.StoredProcedure
指定这样就可以了,
参数采用 SqlParameter[] 数组,
执行和拼接字符串一样的.

热点排行