首页 > 数据库 > SQL Server > 正文

连接sql server、插入数据、从数据库获取时间(C#)

2024-08-31 00:55:46
字体:
来源:转载
供稿:网友
连接sql server、插入数据、从数据库获取时间(C#)
using System;using System.Data.SqlClient;namespace Test{    //连接数据库    public class Connection    {        PRivate static string connectionString =            "Server = 192.168.1.222;" +            "Database = Test;" +            "User ID = Test;" +            "PassWord = abc123;";        /// <summary>        /// 连接数据库        /// </summary>        /// <returns></returns>        private SqlConnection ConnectionOpen()        {            SqlConnection conn = new SqlConnection(connectionString);            conn.Open();            return conn;        }        /// <summary>        /// 向表(Table)中插入一条数据        /// </summary>        public void Insert(string value1, string value2, string value3, DateTime dateTime)        {            SqlConnection conn = ConnectionOpen();            string sql =                "insert into Table(row1, row2, row3, DateTime) values ('" +                value1 + "', '" + value2 + "', '" + value3 + "', '" + dateTime + "')";            SqlCommand comm = new SqlCommand(sql, conn);            comm.ExecuteReader();              conn.Close();        }        /// <summary>        /// 从数据库中获取当前时间        /// </summary>        /// <returns></returns>        public DateTime GetDateTimeFromSQL()        {            SqlConnection conn = ConnectionOpen();            string sql = "select getdate()";            SqlCommand comm = new SqlCommand(sql, conn);            SqlDataReader reader = comm.ExecuteReader();            DateTime dt;            if (reader.Read())            {                dt = (DateTime)reader[0];                conn.Close();                return dt;            }            conn.Close();            return DateTime.MinValue;        }    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表