千家信息网

C#连接到SQL Server,SQLite数据库

发表于:2025-02-02 作者:千家信息网编辑
千家信息网最后更新 2025年02月02日,C#中连接SQL Server的代码:string con, sql; con = "Server=.;Database=温湿度测试;Trusted_Connection=SSPI"; sql =
千家信息网最后更新 2025年02月02日C#连接到SQL Server,SQLite数据库

C#中连接SQL Server的代码:

string con, sql;  con = "Server=.;Database=温湿度测试;Trusted_Connection=SSPI";  sql = "select * from 温湿度测试";  SqlConnection mycon = new SqlConnection(con);  DateTime uploadDate = System.DateTime.Now;  mycon.Open();  SqlDataAdapter myda = new SqlDataAdapter(sql, con);  DataSet myds = new DataSet();  myda.Fill(myds, "温湿度测试");    String sql2 = "insert into 温湿度测试(日期,时间,温度,湿度) values('" + uploadDate + "','" + uploadDate + "','" + wendu + "','" + shidu + "')";  SqlDataAdapter myda2 = new SqlDataAdapter(sql2, mycon);  myda2.Fill(myds, "温湿度测试");    dataGridView1.DataSource = myds.Tables["温湿度测试"];  mycon.Close();

下面是C#链接SQLite的代码:

//sqlite 数据库  string uploadDate = System.DateTime.Now.ToShortDateString().ToString();  string uploadTime = System.DateTime.Now.ToLongTimeString().ToString();  SQLiteConnection conn = null;    string dbPath = "Data Source =" + "C:/sqlite" + "/数据测试.db";  conn = new SQLiteConnection(dbPath);//创建数据库实例,指定文件位置    conn.Open();//打开数据库,若文件不存在会自动创建      string sql = "CREATE TABLE IF NOT EXISTS '" + "温度" + uploadDate + "' (日期 varchar(6), 时间 varchar(6), 温度 varchar(6));";//建表语句    SQLiteCommand cmdCreateTable = new SQLiteCommand(sql, conn);  cmdCreateTable.ExecuteNonQuery();//如果表不存在,创建数据表      SQLiteCommand cmdInsert = new SQLiteCommand(conn);  cmdInsert.CommandText = "INSERT INTO '" + "温度" + uploadDate + "'  VALUES('" + uploadDate + "','" + uploadTime + "','" + wendu + "')";//插入几条数据    cmdInsert.ExecuteNonQuery();    conn.Close();


0