WinForm数据库操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public class DataClass
    {
        public static SqlConnection getconnection()
        {
            string strConn = @"Data Source=name;Initial Catalog=C:\……\STUDENTSINFODATABASE.MDF;Persist Security Info=True;User ID=sa;password=123";
            return new SqlConnection(strConn);
        }

        public static void CommandSQLData(string SQL)
        {
            SqlConnection conn = getconnection();
            conn.Open();
            try
            {
                SqlCommand cmd = new SqlCommand(SQL, conn);
                string SQLCommandType = null;
                string SQLToLower = SQL.Trim().ToLower();
                if (SQLToLower.StartsWith("insert"))
                {
                    SQLCommandType = "添加";
                }
                else if (SQLToLower.StartsWith("update"))
                {
                    SQLCommandType = "修改";
                }
                else if (SQLToLower.StartsWith("delete"))
                {
                    SQLCommandType = "删除";
                }
                else
                {
                    SQLCommandType = "数据操作";
                }

                if (cmd.ExecuteNonQuery() > 0)
                {
                    MessageBox.Show(SQLCommandType+"成功!", "提示");
                }
                else
                {
                    MessageBox.Show(SQLCommandType+"失败!", "提示");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误");
            }
            finally
            {
                conn.Close();
            }
        }

}

posted @ 2013-06-03 15:18  三颗咸鸭蛋  阅读(217)  评论(0编辑  收藏  举报