| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 619 人关注过本帖
标题:(求助)往数据库中存数据的函数,求各位大神指导!
只看楼主 加入收藏
xlt0703
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2013-4-13
结帖率:0
收藏
已结贴  问题点数:20 回复次数:3 
(求助)往数据库中存数据的函数,求各位大神指导!
本人大菜鸟。。。。写个程序串口接受的数据放入数据库中,数据库已建好
写入数据的save data函数好像错了,运行会这样
[local]1[/local]

求各位大神帮忙修改程序,谢谢谢谢谢谢。。。。这是save data函数
  public void SaveData()
        {
            string sql;
            string[] str = new string[5];
            sql = "select count(*) as cnt from data ";
            OleDbCommand cmd1 = new OleDbCommand(sql, con);
            int cnt = int.Parse(cmd1.ExecuteScalar().ToString()) + 1;
            str[0] = cnt.ToString();
            str[1] = Int32.Parse(tmp[5] + tmp[4], System.Globalization.NumberStyles.HexNumber).ToString();
            str[2] = Int32.Parse(tmp[8] + tmp[9], System.Globalization.NumberStyles.HexNumber).ToString();
            switch (Int32.Parse(tmp[8] + tmp[9], System.Globalization.NumberStyles.HexNumber))
            {
                //加速度
                case 3843: str[3] = Int32.Parse(tmp[10] + tmp[11], System.Globalization.NumberStyles.HexNumber) + ":" + Int32.Parse(tmp[12] + tmp[13], System.Globalization.NumberStyles.HexNumber).ToString() + ":" + Int32.Parse(tmp[14] + tmp[15], System.Globalization.NumberStyles.HexNumber).ToString();
                    flag[1]++;
                    //timer2.Enabled = true;
                    if (flag[1] == 5)
                    {
                        flag[1] = 0;
                        //timer2.Enabled = false;
                    }
                    break;

                default:
                    break;
            }
            str[4] = System.DateTime.Now.Year.ToString() + ":" + System.DateTime.Now.Month.ToString() + ":" + System.DateTime.Now.Day.ToString() + ":" + System.DateTime.Now.Hour.ToString() + ":" + System.DateTime.Now.Minute.ToString() + ":" + System.DateTime.Now.Second.ToString();
            sql = "insert into data values" + @"('" + str[0] + "','" + str[1] + "','" + str[2] + "','" + str[3] + "','" + str[4] + "')";
            OleDbCommand cmd = new OleDbCommand(sql, con);
            cmd.ExecuteNonQuery();

            sql = "select nodeid from node where nodeid='" + str[1] + "'";

            OleDbCommand cmd5 = new OleDbCommand(sql, con);
            OleDbDataReader rd = cmd5.ExecuteReader();
            bool j = rd.HasRows;

            if (j == false)
            {
                sql = "insert into node(" + "nodeid" + "," + "status" + ")" + "values('" + str[1] + "','" + "online" + "')";
                OleDbCommand cmd2 = new OleDbCommand(sql, con);
                cmd2.ExecuteNonQuery();
            }
            else
            {
                sql = "update node set status ='online'where nodeid='" + str[1] + "'";
                OleDbCommand cmd6 = new OleDbCommand(sql, con);
                cmd6.ExecuteNonQuery();
            }


            DataSet dataSet = new DataSet();
            OleDbCommand cmd8 = con.CreateCommand();
             = "select sensorid from nsrelation where sensorid='" + Int32.Parse(tmp[8] + tmp[9], System.Globalization.NumberStyles.HexNumber).ToString() + "'";
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd8);
            adapter.Fill(dataSet);
            if (dataSet.Tables[0].Rows.Count == 0)
            {

                sql = "insert into nsrelation(" + "nodeid" + "," + "sensorid" + ")" + "values('" + str[1] + "','" + Int32.Parse(tmp[8] + tmp[9], System.Globalization.NumberStyles.HexNumber).ToString() + "')";
                OleDbCommand cmd3 = new OleDbCommand(sql, con);
                cmd3.ExecuteNonQuery();
            }
            else
            {
                sql = "update nsrelation set nodeid ='" + str[1] + "'where sensorid='" + Int32.Parse(tmp[8] + tmp[9], System.Globalization.NumberStyles.HexNumber).ToString() + "'";
                OleDbCommand cmd7 = new OleDbCommand(sql, con);
                cmd7.ExecuteNonQuery();
            }

            sql = "update sensor set status ='online'where sensorid='" + str[2] + "'";
            OleDbCommand cmd4 = new OleDbCommand(sql, con);
            cmd4.ExecuteNonQuery();

        }
搜索更多相关主题的帖子: 数据库 数据 public count 
2013-04-13 23:38
xlt0703
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2013-4-13
收藏
得分:0 
图片貌似显示不了,那我就打出来好了,运行以后messagebox显示exectuescalar 要求可已打开且可用的connections。连接的当前状态为已关闭
2013-04-13 23:43
shangsharon
Rank: 9Rank: 9Rank: 9
来 自:湖北武汉
等 级:蜘蛛侠
威 望:7
帖 子:221
专家分:1261
注 册:2012-3-25
收藏
得分:20 
数据连接未打开.
con.open();
2013-04-14 01:31
lxb932979339
Rank: 5Rank: 5
等 级:职业侠客
威 望:4
帖 子:84
专家分:313
注 册:2013-4-24
收藏
得分:0 
乱了,几乎相同的代码,写这么多次,你不觉得特别乱么,要懂得用方法封装起来调用,给你段代码,虽然不太规范,先按照这个来写吧


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            BookModel model = new BookModel();
            Console.WriteLine("请输入书籍类别号");
            model.FName = Console.ReadLine();
            Console.WriteLine("请输入书籍类别号");
            model.FCategoryID = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("请输入作者名称");
            model.FAuthor = Console.ReadLine();
            Console.WriteLine("请输入出版日期");
            model.FYearPublished = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("请输入是否删除(false/ture)");
            model.IsDel = Convert.ToBoolean(Console.ReadLine());

            int rel = new Program().Add(model);//因为静态方法不能直接调用非静态方法,所以要实例化一个新的对象进行调用
            List<BookModel> list = new List<BookModel>();
            list = (List<BookModel>)(new Program().Table());
            foreach (BookModel m in list)
            {
                Console.WriteLine(m.FAuthor.ToString());
                Console.WriteLine(m.FCategoryID.ToString());
                Console.WriteLine(m.FId.ToString());
                Console.WriteLine(m.FName.ToCharArray());
                Console.WriteLine(m.FYearPublished.ToString());
                Console.WriteLine(m.IsDel.ToString());
            }
            Console.ReadKey();
        }
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
         public int Add(BookModel model)
        {
            string sqlText = "insert into T_Book(FAuthor,FCategoryID,FName,FYearPublished,IsDel)values(@FAuthor,@FCategoryID,@FName,@FYearPublished,@IsDel);select @@identity";
            object rel = SqlHelper.ExecuteScalar(sqlText, new SqlParameter("FAuthor", ModelItemIsNow(model.FAuthor)),
                new SqlParameter("FCategoryID", ModelItemIsNow(model.FCategoryID)),
                new SqlParameter("FName", ModelItemIsNow(model.FName)),
                new SqlParameter("FYearPublished", ModelItemIsNow(model.FYearPublished)),
                new SqlParameter("IsDel", ModelItemIsNow(model.IsDel)));
            return Convert.ToInt32(rel);
        }
         public IEnumerable<BookModel> Table()
         {
             string sqlText = "select * from T_Book";
             DataTable tb = new DataTable();
             tb = SqlHelper.ExecuteDataTable(sqlText);
             List<BookModel> list = new List<BookModel>();
             foreach (DataRow row in tb.Rows)
             {
                 BookModel model = new BookModel();
                 model.FAuthor = row.IsNull("FAuthor") ? null : (string)row["FAuthor"];
                 model.FCategoryID = row.IsNull("FCategoryID") ? null : (int?)row["FCategoryID"];
                 model.FId = (int)row["FId"];//因为FID是主健字段,所以一定是非空字段
                 model.FName = row.IsNull("FName") ? null : (string)row["FName"];
                 model.FYearPublished = row.IsNull("FYearPublished") ? null : (int?)row["FYearPublished"];
                 model.IsDel = row.IsNull("IsDel") ? null : (bool?)row["IsDel"];
                 list.Add(model);
             }
             return list;
         }

        /// <summary>
        /// 判断传递的参数是否为空,若为空,返回DBNULL的值
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public object ModelItemIsNow(object str)
        {
            if (str == null || str.ToString().Trim ().Length <= 0)
            {
                return DBNull.Value;
            }
            else
            {
                return str;
            }
        }
    }
    class SqlHelper
    {
        private static readonly string conStr = "Data Source=.;Initial Catalog=one;Persist Security Info=True;User ID=sa;Password=liuxianbin123";
        private static SqlConnection con;
        /// <summary>
        /// 创建数据库连接
        /// </summary>
        public static SqlConnection Con
        {
            get
            {
                if (con == null || con.State == ConnectionState.Broken)
                {
                    con = new SqlConnection(conStr);
                }
                return con;
            }
        }

        public static DataTable ExecuteDataTable(string sqlText, params SqlParameter[] parameter)
        {
            SqlCommand com = new SqlCommand(sqlText, Con);
             = CommandType.Text;
            if (parameter != null || parameter.Length > 0)
            {
                com.Parameters.AddRange(parameter);
            }
            SqlDataAdapter ad = new SqlDataAdapter(com);
            DataTable tb = new DataTable();
            try
            {
                ad.Fill(tb);
                return tb;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public static object ExecuteScalar(string sqlText, params SqlParameter[] parameter)
        {
            Con.Open();
            SqlCommand com = new SqlCommand(sqlText, Con);
            if (parameter.Length > 0 || parameter != null)
            {
                com.Parameters.AddRange(parameter);
            }
            try
            {
                return com.ExecuteScalar();
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                Con.Close();
            }
        }
        public static int ExecuteNonQury(string sqlText, params SqlParameter[] parameter)
        {
            Con.Open();
            SqlCommand com = new SqlCommand(sqlText, Con);
            if (parameter.Length > 0 || parameter != null)
            {
                com.Parameters.AddRange(parameter);
            }
            try
            {
                return com.ExecuteNonQuery();
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                Con.Close();
            }
        }
    }
    class BookModel
    {
        private int fId;

        public int FId
        {
            get { return fId; }
            set { fId = value; }
        }
        private string fName;

        public string FName
        {
            get { return fName; }
            set { fName = value; }
        }
        private int? fYearPublished;

        public int? FYearPublished
        {
            get { return fYearPublished; }
            set { fYearPublished = value; }
        }
        private int? fCategoryID;

        public int? FCategoryID
        {
            get { return fCategoryID; }
            set { fCategoryID = value; }
        }
        private bool? isDel;

        public bool? IsDel
        {
            get { return isDel; }
            set { isDel = value; }
        }
        private string fAuthor;

        public string FAuthor
        {
            get { return fAuthor; }
            set { fAuthor = value; }
        }
    }
}

[ 本帖最后由 lxb932979339 于 2013-4-24 05:57 编辑 ]
2013-04-24 05:55
快速回复:(求助)往数据库中存数据的函数,求各位大神指导!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.034746 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved