1.连接SQL Server常用方法
方法 | 解释 | 方法 | 解释 |
SqlConnection() | 创建数据库连接对象 | open() | 打开数据库连接 |
close() | 关闭数据库连接 | ConnectionString | 设置连接字符串 |
2.数据库操作常用方法
方法 | 解释 | 方法 | 解释 |
SqlCommand(string sql, SqlConnection con) | 表示要对数据库执行的一个 Transact-SQL 语句或存储过程 | ExecteNonQuery() | 执行操作 |
SqlDataReader() | 数据读取对象 | SqlDataReader ExecteNonReader() | 返回一个数据读取对象类型参数。执行数据的读取,每次返回一行 |
具体实例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Connection
{
private SqlConnection con = null;
public void openConnection(String str)
{
con = new SqlConnection();
con.ConnectionString = str;
con.Open();
}
public void closeConnection()
{
con.Close();
}
public bool insert(string id, string name)
{
bool flag = false;
string sql = String.Format("insert into demo values('{0}', '{1}')", id, name);
using (SqlCommand cmd = new SqlCommand(sql, this.con))
{
int row = cmd.ExecuteNonQuery();
if (row > 0)
{
flag = true;
}
}
return flag;
}
public bool delete(string id)
{
bool flag = false;
string sql = String.Format("delete from demo where id = '{0}'", id);
using (SqlCommand cmd = new SqlCommand(sql, this.con))
{
int row = cmd.ExecuteNonQuery();
if (row > 0)
{
flag = true;
}
}
return flag;
}
public bool update(string id, string name)
{
bool flag = false;
string sql = String.Format("update demo set name = '{0}' where id = '{1}'", id, name);
using (SqlCommand cmd = new SqlCommand(sql, this.con))
{
int row = cmd.ExecuteNonQuery();
if (row > 0)
{
flag = true;
}
}
return flag;
}
public void select(string id, string name)
{
string sql = "select * from demo";
SqlCommand cmd = new SqlCommand(sql, this.con);
using (SqlDataReader rd = cmd.ExecuteReader())
{
while(rd.Read()){
for(int i = 0; i < rd.FieldCount; i++){
Console.Write(rd[i]);
}
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
string str = "Data Source=localhost; Initial Catalog=test;User ID=sa;Password=123456";
Connection con = new Connection();
con.openConnection(str);
}
}
}