C#连接数据库
VScode 配置C#开发环境
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; namespace ADODome { class Program { static void Main(string[] args) { string connString_1 = @"server=.\SQLEXPRESS;uid=sa;pwd=123456;database=Stu"; SqlConnection conn = new SqlConnection(connString_1); conn.Open(); if (ConnectionState.Open == conn.State) { Console.WriteLine("Connection is Opend!"); } conn.Close(); if(ConnectionState.Closed == conn.State) { Console.WriteLine("Connection is close!"); } } } }
封装类
class SqlHelp { private static string str = @"server=.\SQLEXPRESS;uid=sa;pwd=123456;database=Stu"; public static object GetSingleResult(String sql) { SqlConnection conn = new SqlConnection(str); SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); object result = cmd.ExecuteScalar(); conn.Close(); return result; } public static int Update(String sql) { SqlConnection conn = new SqlConnection(str); SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); int result = cmd.ExecuteNonQuery(); conn.Close(); return result; } public static SqlDataReader GetReader(String sql) { SqlConnection conn = new SqlConnection(str); SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); //CommandBehavior.CloseConnection //不使用conn.close() SqlDataReader result = cmd.ExecuteReader(CommandBehavior.CloseConnection); return result; } }
调用封装类
public int AddStudent( string name) { //"insert into student values('{0}');select @@identity"; string sql = "insert into student values('{0}');select @@identity"; sql = string.Format(sql, name); return SqlHelp.Update(sql); } public void GetStu(int age) { string sql = "select * from student where age="+age; SqlDataReader reader = SqlHelp.GetReader(sql); while (reader.Read()) { Console.WriteLine("age:"+reader["age"] +";\tname:"+reader["name"]); } reader.Close(); }
本文来自博客园踩坑狭,作者:韩若明瞳,转载请注明原文链接:https://www.cnblogs.com/han-guang-xue/p/10522687.html