一佳一

记录像1+1一样简洁的代码

导航

C#获取MySql 数据常用的代码

Posted on 2016-03-31 15:44  一佳一  阅读(2771)  评论(0编辑  收藏  举报

1.读取

public DataTable ExecuteDataTable(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySqlDataAdapter command = new MySqlDataAdapter(cmd);
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds.Tables[0];
}
}

2.使用SET IDENTITY_INSERT手动为数据库自增字段插入编号

    string sqlstr = "SET IDENTITY_INSERT t1 ON;";
                lists.Add(sqlstr);
                sqlstr = "INSERT INTO t1       (id, name) VALUES ("+i.ToString()+", '" + i.ToString()+"');";
                lists.Add(sqlstr);
                sqlstr = "set identity_insert t1 off;";
                lists.Add(sqlstr);

                da.SqlCeExecuteNonQuery(lists);

 public void SqlCeExecuteNonQuery(List<string> lists)
        {
            SqlCeConnection conn = new SqlCeConnection();
            SqlCeCommand comm = null;
            try
            {
                conn.ConnectionString = PDAConnectionLocStr;
                conn.Open();
                comm = new SqlCeCommand("", conn);
                for (int i = 0; i < lists.Count; i++)
                {
                    comm.CommandText = lists[i];
                    comm.ExecuteNonQuery();
                }

            }
            catch (SqlCeException ex)
            {

            }
            finally
            {
                conn.Close();
                conn.Dispose();
                comm.Dispose();
            }
        }
 

3.mysql数据Unix时间戳与C# DateTime时间类型互换

dangranusing System;
using System.Collections.Generic;
using System.Text;

namespace WWFramework.DateTimes
{
    /// <summary>
    /// 时间相关函数
    /// </summary>
    public static class Function
    {
        /// <summary>
        /// 将Unix时间戳转换为DateTime类型时间
        /// </summary>
        /// <param name="d">double 型数字</param>
        /// <returns>DateTime</returns>
        public static System.DateTime ConvertIntDateTime(double d)
        {
             System.DateTime time = System.DateTime.MinValue;
             System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
             time = startTime.AddSeconds(d);
            return time;
         }

        /// <summary>
        /// 将c# DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns>double</returns>
        public static double ConvertDateTimeInt(System.DateTime time)
        {
            double intResult = 0;
             System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
             intResult = (time - startTime).TotalSeconds;
            return intResult;
         }
     }
}