工具:
1.Visual Studio (我使用的是vs2013)
2.SQL Server (我使用的是sql server2008)
操作:
1.打開sql sever數據庫,打開后會看到數據庫的初始界面,復制服務器名稱:
2.打開VS2013,點擊工具下的連接數據庫:
3.測試連接成功后點擊服務器資源管理器,會看到有下圖信息,點擊“表”可以看到數據庫里面創建的數據表:
連接代碼:
現在我們把數據庫添加到了vs里,要想對數據庫進行增刪改查操作,還需要寫一些代碼實現。
工具類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace DAL
{
public class DBhelp
{
private DBhelp() { }
private static DBhelp dbhelp = null;
public static DBhelp Create()
{
if (dbhelp == null)
dbhelp = new DBhelp();
return dbhelp;
}
string conString = ConfigurationManager.ConnectionStrings["a"].ConnectionString;
//返回一行一列
public int ExecuteScalar(string sql, params SqlParameter[] sp)
{
SqlConnection con = new SqlConnection(conString);
try
{
con.Open();
SqlCommand com = new SqlCommand(sql, con);
com.Parameters.AddRange(sp);
return (int)com.ExecuteScalar();
}
catch (Exception)
{
con.Close();
throw;
}
finally
{
con.Close();
}
}
//返回讀取器對象
public SqlDataReader ExecuteReader(string sql, params SqlParameter[] sp)
{
SqlConnection con = new SqlConnection(conString);
try
{
con.Open();
SqlCommand com = new SqlCommand(sql, con);
com.Parameters.AddRange(sp);
return com.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
con.Close();
throw ex;
}
}
//返回數據集,
public DataSet ExecuteAdater(string sql, params SqlParameter[] sp)
{
SqlConnection con = new SqlConnection(conString);
try
{
SqlCommand com = new SqlCommand(sql, con);
com.Parameters.AddRange(sp);
SqlDataAdapter adapter = new SqlDataAdapter(com);
DataSet ds = new DataSet();
adapter.Fill(ds, "a");
return ds;
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}
//返回受影響行數
public int ExecuteNonQuery(string sql, CommandType type = CommandType.Text, params SqlParameter[] sp)
{
SqlConnection con = new SqlConnection(conString);
try
{
con.Open();
SqlCommand com = new SqlCommand(sql, con);
com.Parameters.AddRange(sp);
com.CommandType = type;
return com.ExecuteNonQuery();
}
catch (Exception)
{
con.Close();
throw;
}
finally
{
con.Close();
}
}
}
}
修改代碼里的 string conString = ConfigurationManager.ConnectionStrings["a"].ConnectionString; 這一步用來連接數據庫,至關重要。
在服務資源管理器中選中數據庫,然后在右下角屬性中找到連接字符串,復制內容。
修改APP.config:
將connectionString的內容修改為剛剛復制的連接字符串。
完成這些操作后,就可以用代碼操作數據庫了。