连接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; } } }

 

posted @ 2014-05-06 10:53  疯人愿  阅读(3886)  评论(0编辑  收藏  举报