本文整理汇总了C#中System.Data.SqlClient.SqlConnection类的典型用法代码示例。如果您正苦于以下问题:C# SqlConnection类的具体用法?C# SqlConnection怎么用?C# SqlConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SqlConnection类属于System.Data.SqlClient命名空间,在下文中一共展示了SqlConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetHandoverLogByHandoverLogId
public static DataTable GetHandoverLogByHandoverLogId(int handoverLogId)
{
string connectionString = ConnectionStringFactory.GetNXJCConnectionString();
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = @"SELECT WorkingTeamShiftLog.*,
StaffInfo.Name AS ChargeManName, ProductLine.Name AS ProductLineName,
WorkingTeam.Name AS WorkingTeamName
FROM WorkingTeam INNER JOIN
StaffInfo INNER JOIN
WorkingTeamShiftLog ON StaffInfo.ID = WorkingTeamShiftLog.ChargeManID INNER JOIN
ProductLine ON WorkingTeamShiftLog.ProductLineID = ProductLine.ID ON
WorkingTeam.ID = WorkingTeamShiftLog.WorkingTeamID
WHERE (WorkingTeamShiftLog.ID = @workingTeamShiftLogID)";
command.Parameters.Add(new SqlParameter("workingTeamShiftLogID", handoverLogId));
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
}
return ds.Tables[0];
}
示例2: Main
public static void Main()
{
using (SqlConnection dbcon = new SqlConnection(ImageExtracter.ConnectionString))
{
dbcon.Open();
SqlCommand command = new SqlCommand("SELECT Picture FROM Categories", dbcon);
var reader = command.ExecuteReader();
var counter = 0;
while (reader.Read())
{
byte[] imageByteArray = (byte[])reader["Picture"];
const int oleMetaPictStartPosition = 78;
var memoryStream =
new MemoryStream(imageByteArray, oleMetaPictStartPosition,
imageByteArray.Length - oleMetaPictStartPosition);
using (memoryStream)
{
using (var image = Image.FromStream(memoryStream, true, true))
{
image.Save("../../picture" + (++counter) + ".jpg");
}
}
}
}
Console.WriteLine("Images exported successfully!");
Console.WriteLine("See project folder for results!");
}
示例3: DataPortal_Insert
protected override void DataPortal_Insert()
{
bool cancel = false;
OnInserting(ref cancel);
if (cancel) return;
const string commandText = "INSERT INTO [dbo].[Category] ([CategoryId], [Name], [Descn]) VALUES (@p_CategoryId, @p_Name, @p_Descn)";
using (var connection = new SqlConnection(ADOHelper.ConnectionString))
{
connection.Open();
using(var command = new SqlCommand(commandText, connection))
{
command.Parameters.AddWithValue("@p_CategoryId", this.CategoryId);
command.Parameters.AddWithValue("@p_Name", ADOHelper.NullCheck(this.Name));
command.Parameters.AddWithValue("@p_Descn", ADOHelper.NullCheck(this.Description));
//result: The number of rows changed, inserted, or deleted. -1 for select statements; 0 if no rows were affected, or the statement failed.
int result = command.ExecuteNonQuery();
if (result == 0)
throw new DBConcurrencyException("The entity is out of date on the client. Please update the entity and try again. This could also be thrown if the sql statement failed to execute.");
LoadProperty(_originalCategoryIdProperty, this.CategoryId);
}
FieldManager.UpdateChildren(this, connection);
}
OnInserted();
}
示例4: EnumerateClients
public IEnumerable<UserInfoShort> EnumerateClients(string fio, string login, int pageNumber, int countPerPage)
{
using (var connection = new SqlConnection(_configurationService.DatabaseConnectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_EnumerateClients";
command.Parameters.AddWithValue("@FIO", fio ?? (object)DBNull.Value).SqlDbType = SqlDbType.NVarChar;
command.Parameters.AddWithValue("@Login",
login != null ? login.ToLower() : (object)DBNull.Value).SqlDbType = SqlDbType.NVarChar;
command.Parameters.AddWithValue("@PageNumber", pageNumber).SqlDbType = SqlDbType.Int;
command.Parameters.AddWithValue("@CountPerPage", countPerPage).SqlDbType = SqlDbType.Int;
connection.Open();
using (var reader = command.ExecuteReader())
{
var lst = new List<UserInfoShort>();
while (reader.Read())
{
lst.Add(new UserInfoShort
{
UserId = (Guid)reader["UserId"],
CounOfCardAccounts = (int)reader["CounOfCardAccounts"],
FIO = (string)reader["FIO"],
Login = (string)reader["Login"],
RegistrationDate = (DateTime)reader["RegistrationDate"]
});
}
return lst;
}
}
}
}
示例5: PH_BHTrans_Calc
public static int PH_BHTrans_Calc(string strConnDB, string strYearWeek)
{
try
{
int rtn = 0;
using (SqlConnection sqlConn = new SqlConnection(strConnDB))
{
if (sqlConn.State == ConnectionState.Closed ) sqlConn.Open();
SqlCommand sqlComm = new SqlCommand("usp_BH_Transaction_Calc", sqlConn);
sqlComm.CommandText = "usp_BH_Transaction_Calc";
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.CommandTimeout = 0;
sqlComm.Parameters.AddRange(new SqlParameter[] { new SqlParameter("@Tesco_Week", strYearWeek) });
rtn = sqlComm.ExecuteNonQuery();
}
//int rtn =
//SqlTransaction sqlTran = new SqlConnection(strConnDB).BeginTransaction();
//SqlHelper.ExecuteNonQuery(strConnDB, CommandType.StoredProcedure, "usp_BH_Transaction_Calc"
// , new SqlParameter[] {new SqlParameter("@Tesco_Week",strYearWeek)
// });
return rtn;
}
catch (Exception ex)
{
throw new Exception("PH_BHTrans_Calc >> " + ex.Message);
}
}
示例6: GetTiposVenda
private DataTable GetTiposVenda()
{
DataTable dataTable = new DataTable();
this.con = new SqlConnection(Security.GetCnn());
string selectCommandText = "";
if (this._dev != "D")
{
selectCommandText = "select tipo_venta_id, descripcion, devolucion from Tipo_venta where devolucion='N'";
}
else
{
selectCommandText = "select tipo_venta_id, descripcion, devolucion from Tipo_venta where devolucion='S'";
}
if ((this.con != null) && (this.con.State == ConnectionState.Open))
{
this.con.Close();
}
this.con.Open();
try
{
new SqlDataAdapter(selectCommandText, this.con).Fill(dataTable);
this.con.Close();
}
catch (Exception)
{
}
return dataTable;
}
示例7: FindProductBy
private static ICollection<string> FindProductBy(string partOfName)
{
var names = new List<string>();
string connectionString = "Data Source=.;Initial Catalog=Northwind;Integrated Security=SSPI;";
var dbCon = new SqlConnection(connectionString);
dbCon.Open();
using (dbCon)
{
SqlCommand command = new SqlCommand(
"SELECT p.ProductName FROM Products p WHERE p.ProductName LIKE @Search", dbCon);
command.Parameters.AddWithValue("@Search", "%" + partOfName + "%");
SqlDataReader reader = command.ExecuteReader();
Console.WriteLine("\nProductNams that contains ({0}):\n", partOfName);
using (reader)
{
string categoryName = string.Empty;
string currentCategoryName = string.Empty;
while (reader.Read())
{
string productName = (string)reader["ProductName"];
names.Add(productName);
}
}
}
return names;
}
示例8: GetOne
public DataSet GetOne(string empresaid, tb_tipimpto BE)
{
using (SqlConnection cnx = new SqlConnection(conex.empConexion(empresaid)))
{
using (SqlCommand cmd = new SqlCommand("gspTbTipimpto_SELECT", cnx))
{
DataSet ds = new DataSet();
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@tipimptoid", SqlDbType.Char, 1).Value = BE.tipimptoid;
}
try
{
cnx.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
return ds;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
示例9: GetAllBootcampTechnologies
public List<BootcampTechnology> GetAllBootcampTechnologies()
{
using (SqlConnection connection = new SqlConnection(Settings.GetConnectionString()))
{
return connection.Query<BootcampTechnology>("BootcampTechnologyGetAll", commandType: CommandType.StoredProcedure).ToList();
}
}
示例10: repositoryItemButtonEditSave_ButtonClick
private void repositoryItemButtonEditSave_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
{
if (MessageBox.Show("هل انت متأكد؟", "تحزيــــر", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
return;
DataRow Row = (DataRow)gridViewMain.GetFocusedDataRow();
SqlConnection con = new SqlConnection(MyCL.SqlConStr);
SqlCommand cmd = new SqlCommand("", con);
try
{
if (Row["knowID"].ToString() == string.Empty)// Is Unsaved Row?
{
string NewID = MyCL.GetNewID("CDknow", "knowID");
cmd.CommandText = string.Format(@"Insert Into CDknow (knowID, know) VALUES ({0}, '{1}')",
NewID, Row["know"]);
}
else
{
cmd.CommandText = string.Format(@"Update CDknow Set know = '{0}' Where knowID = {1}",
Row["know"], Row["knowID"]);
}
con.Open();
cmd.ExecuteNonQuery();
MyCL.ShowMsg("تم الحفظ", false, this);
}
catch (SqlException ex)
{
MyCL.ShowMsg(MyCL.CheckExp(ex), true, this);
}
con.Close();
LoadData();
}
示例11: repositoryItemButtonEditDelete_ButtonClick
private void repositoryItemButtonEditDelete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
{
if (MessageBox.Show("هل انت متأكد؟", "تحزيــــر", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
return;
DataRow Row = (DataRow)gridViewMain.GetFocusedDataRow();
if (Row["knowID"].ToString() == string.Empty)// Is Unsaved Row?
{
LoadData();
return;
}
SqlConnection con = new SqlConnection(MyCL.SqlConStr);
SqlCommand cmd = new SqlCommand("", con);
try
{
cmd.CommandText = @"Delete From CDknow Where knowID = " + Row["knowID"];
con.Open();
cmd.ExecuteNonQuery();
MyCL.ShowMsg("تم الحذف", false, this);
}
catch (SqlException ex)
{
MyCL.ShowMsg(MyCL.CheckExp(ex), true, this);
}
con.Close();
LoadData();
}
示例12: Main
public static void Main()
{
var connection = new SqlConnection(connectionString: "Server=(local); Database=Northwind; Integrated Security=true;");
connection.Open();
var command = new SqlCommand(cmdText: "select c.CategoryName, p.ProductName from Products p inner join Categories c on c.CategoryId = p.CategoryId;", connection: connection);
var categoriesAndProducts = new Dictionary<string, List<string>>();
var reader = command.ExecuteReader();
while (reader.Read())
{
var category = (string)reader["CategoryName"];
var product = (string)reader["ProductName"];
if(categoriesAndProducts.ContainsKey(category))
{
categoriesAndProducts[category].Add(product);
}
else
{
categoriesAndProducts.Add(category, new List<string>());
}
}
connection.Close();
foreach (var kvp in categoriesAndProducts)
{
Console.WriteLine(new string(c: '=', count: 20) + "\n" + kvp.Key + "\n" + new string(c: '=', count: 20));
foreach (var product in kvp.Value)
{
Console.WriteLine("-- " + product);
}
}
}
示例13: load_price
protected void load_price()
{
string price_name = null;
string article = null;
price_name = Request.QueryString["price_name"];
article = Request.QueryString["article"];
if (article != null)
{
if (price_name != null)
{
SqlConnection con = new SqlConnection(str);
string sql = "SELECT id, article, ROUND([price]*(SELECT course FROM Course_USD WHERE id = 1),2) AS [price] FROM " + price_name + " WHERE article=" + article + ";";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
da.Fill(ds, price_name);
DataRow dr;
dr = ds.Tables[price_name].Rows[0];
//Заполняем стоимость товара:
lblprice.Text = dr["price"].ToString();
}
else {Response.Redirect("Error.aspx");}
}
else {Response.Redirect("Error.aspx"); }
}
开发者ID:sgkMoscow,项目名称:vorsinstrument,代码行数:28,代码来源:Zubilo_po_betonu_ploskoe_40x250mm_SDS_plus_Optim.aspx.cs
示例14: Ilceler
public static DataTable Ilceler(int id)
{
try
{
using (baglan = new SqlConnection(ConnectionString))
{
baglan.Open();
using (komutver = new SqlCommand())
{
komutver.Connection = baglan;
komutver.CommandText = "ilce_Listele";
komutver.Parameters.Add("@ilceId", SqlDbType.Int);
komutver.Parameters["@ilceId"].Value = Convert.ToInt32(id);
komutver.CommandType = CommandType.StoredProcedure;
adp = new SqlDataAdapter(komutver);
dt = new DataTable();
adp.Fill(dt);
}
}
}
catch (Exception)
{
throw;
}
return dt;
}
示例15: Sehirler
public static DataTable Sehirler()
{
try
{
using (baglan = new SqlConnection(ConnectionString))
{
baglan.Open();
using (komutver = new SqlCommand())
{
komutver.Connection = baglan;
komutver.CommandText = "sehir_Listele";
komutver.CommandType = CommandType.StoredProcedure;
adp = new SqlDataAdapter(komutver);
dt = new DataTable();
adp.Fill(dt);
}
}
}
catch (Exception)
{
throw;
}
return dt;
}