本文整理汇总了C#中SqlConnection.Open方法的典型用法代码示例。如果您正苦于以下问题:C# SqlConnection.Open方法的具体用法?C# SqlConnection.Open怎么用?C# SqlConnection.Open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SqlConnection
的用法示例。
在下文中一共展示了SqlConnection.Open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetMessagesChat
// Lấy Messages cần gửi
public List<DiscussMessage> GetMessagesChat()
{
var messageChat = new List<MessagesChat>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(@"SELECT dbo.Messages.Id, dbo.Messages.[Content], dbo.Messages.SenderId, dbo.Messages.SendDate, dbo.Messages.Type
FROM dbo.Messages
WHERE dbo.Messages.Sent = 'N' ORDER BY dbo.Messages.SendDate ASC", connection))
{
command.Notification = null;
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
messageChat.Add(item: new MessagesChat
{
Id = reader["Id"].ToString(),
Content = reader["Content"].ToString(),
SenderId = reader["SenderId"].ToString(),
UserName = "",
SendDate = reader["SendDate"].ToString(),
Type = reader["Type"].ToString(),
GroupId = ""
});
}
}
}
return messageChat;
}
示例2: GetPickerData
public static async Task<List<string>> GetPickerData (string make)
{
List<string> result = new List<string>();
using (var conn = new SqlConnection("Server=tcp:willies.database.windows.net,1433;Database=Willies Database;User [email protected];Password=Williescycles1;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"))
{
try
{
conn.Open();
}
catch (Exception e)
{
}
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("SELECT DISTINCT YR FROM Parts Where Make LIKE 'H%'", conn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
result.Add(myReader.GetString(0));
}
conn.Close();
}
return result;
}
示例3: OpenBadConnection
private static void OpenBadConnection(string connectionString, string errorMessage)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
DataTestClass.AssertThrowsWrapper<SqlException>(() => conn.Open(), errorMessage);
}
}
示例4: Fill_User_Header
protected void Fill_User_Header()
{
DataView view = null;
SqlConnection con;
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/BitOp");
System.Configuration.ConnectionStringSettings connString;
connString = rootWebConfig.ConnectionStrings.ConnectionStrings["BopDBConnectionString"];
con = new SqlConnection(connString.ToString());
cmd.Connection = con;
con.Open();
string sql = @"SELECT Fecha_Desde, Inicio_Nombre, Region, Supervisor
FROM Criterios
WHERE Criterio_ID = " + @Criterio_ID;
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
dt = ds.Tables[0];
view = new DataView(dt);
foreach (DataRowView row in view)
{
Lbl_Fecha_Desde.Text = row["Fecha_Desde"].ToString("dd-MM-yyyy");
Lbl_Inicio_Descrip.Text = row["Inicio_Nombre"].ToString();
Lbl_Region.Text = row["Region"].ToString();
Lbl_Supervisor.Text = row["Supervisor"].ToString();
}
con.Close();
}
示例5: EnvironmentHostNameTest
public static void EnvironmentHostNameTest()
{
SqlConnectionStringBuilder builder = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { Pooling = true });
builder.ApplicationName = "HostNameTest";
using (SqlConnection sqlConnection = new SqlConnection(builder.ConnectionString))
{
sqlConnection.Open();
using (SqlCommand command = new SqlCommand("sp_who2", sqlConnection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int programNameOrdinal = reader.GetOrdinal(COL_PROGRAM_NAME);
string programName = reader.GetString(programNameOrdinal);
if (programName != null && programName.Trim().Equals(builder.ApplicationName))
{
// Get the hostname
int hostnameOrdinal = reader.GetOrdinal(COL_HOSTNAME);
string hostnameFromServer = reader.GetString(hostnameOrdinal);
string expectedMachineName = Environment.MachineName.ToUpper();
string hostNameFromServer = hostnameFromServer.Trim().ToUpper();
Assert.Matches(expectedMachineName, hostNameFromServer);
return;
}
}
}
}
}
Assert.True(false, "No non-empty hostname found for the application");
}
示例6: submitButtonH_Click
private void submitButtonH_Click(object sender, EventArgs e)
{
//If this is valid then close the panel and show the info
//Check if this barcode exists in the database
//This code is the same in ever single station other than what data it should pull
SqlConnection connection = new SqlConnection(Properties.Settings.Default.TigerCheckProductionConnectionString);
SqlCommand ifExists = new SqlCommand("IF Exists(Select 1 From TigerCheckProduction.dbo.PatientRecords WHERE [ID_Num] = @barcodeNum) Select 1 Else Select 0", connection);
ifExists.Parameters.AddWithValue("@barcodeNum", barcodeTextBox.Text);
connection.Open();
if (Convert.ToInt32(ifExists.ExecuteScalar()) == 1)
{
barcodePanel.Visible = false;
//Since it exists, make a new patient object and load the data
patient.getPatientData(Convert.ToInt32(barcodeTextBox.Text));
Hearing.Text = patient.Hearing.ToString();
}
else
{
MessageBox.Show("Invalid barcode number");
}
connection.Close();
}
示例7: KillConnectionTest
/// <summary>
/// Tests if killing the connection using the InternalConnectionWrapper is working
/// </summary>
/// <param name="connectionString"></param>
private static void KillConnectionTest(string connectionString)
{
InternalConnectionWrapper wrapper = null;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
wrapper = new InternalConnectionWrapper(connection);
using (SqlCommand command = new SqlCommand("SELECT 5;", connection))
{
DataTestUtility.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result.");
}
wrapper.KillConnection();
}
using (SqlConnection connection2 = new SqlConnection(connectionString))
{
connection2.Open();
Assert.False(wrapper.IsInternalConnectionOf(connection2), "New connection has internal connection that was just killed");
using (SqlCommand command = new SqlCommand("SELECT 5;", connection2))
{
DataTestUtility.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result.");
}
}
}
示例8: BasicParallelTest
private void BasicParallelTest(string connectionString, string tempTableName)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction trans1 = connection.BeginTransaction();
SqlTransaction trans2 = connection.BeginTransaction();
SqlTransaction trans3 = connection.BeginTransaction();
SqlCommand com1 = new SqlCommand("select top 1 au_id from " + tempTableName, connection);
com1.Transaction = trans1;
com1.ExecuteNonQuery();
SqlCommand com2 = new SqlCommand("select top 1 au_id from " + tempTableName, connection);
com2.Transaction = trans2;
com2.ExecuteNonQuery();
SqlCommand com3 = new SqlCommand("select top 1 au_id from " + tempTableName, connection);
com3.Transaction = trans3;
com3.ExecuteNonQuery();
trans1.Rollback();
trans2.Rollback();
trans3.Rollback();
com1.Dispose();
com2.Dispose();
com3.Dispose();
}
}
示例9: PrepareCommand
private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] parms)
{
if (connection.State != ConnectionState.Open) connection.Open();
command.Connection = connection;
command.CommandTimeout = CommandTimeOut;
// 设置命令文本(存储过程名或SQL语句)
command.CommandText = commandText;
// 分配事务
if (transaction != null)
{
command.Transaction = transaction;
}
// 设置命令类型.
command.CommandType = commandType;
if (parms != null && parms.Length > 0)
{
//预处理SqlParameter参数数组,将为NULL的参数赋值为DBNull.Value;
foreach (SqlParameter parameter in parms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
}
command.Parameters.AddRange(parms);
}
}
示例10: BasicConnectionPoolingTest
/// <summary>
/// Tests that using the same connection string results in the same pool\internal connection and a different string results in a different pool\internal connection
/// </summary>
/// <param name="connectionString"></param>
private static void BasicConnectionPoolingTest(string connectionString)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
InternalConnectionWrapper internalConnection = new InternalConnectionWrapper(connection);
ConnectionPoolWrapper connectionPool = new ConnectionPoolWrapper(connection);
connection.Close();
SqlConnection connection2 = new SqlConnection(connectionString);
connection2.Open();
Assert.True(internalConnection.IsInternalConnectionOf(connection2), "New connection does not use same internal connection");
Assert.True(connectionPool.ContainsConnection(connection2), "New connection is in a different pool");
connection2.Close();
SqlConnection connection3 = new SqlConnection(connectionString + ";App=SqlConnectionPoolUnitTest;");
connection3.Open();
Assert.False(internalConnection.IsInternalConnectionOf(connection3), "Connection with different connection string uses same internal connection");
Assert.False(connectionPool.ContainsConnection(connection3), "Connection with different connection string uses same connection pool");
connection3.Close();
connectionPool.Cleanup();
SqlConnection connection4 = new SqlConnection(connectionString);
connection4.Open();
Assert.True(internalConnection.IsInternalConnectionOf(connection4), "New connection does not use same internal connection");
Assert.True(connectionPool.ContainsConnection(connection4), "New connection is in a different pool");
connection4.Close();
}
示例11: TestMain
public static void TestMain()
{
string connstr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString;
string cmdText1 = "select * from Orders; select count(*) from Customers";
string cmdText2 = "select * from Customers; select count(*) from Orders";
using (var conn = new SqlConnection(connstr))
{
conn.Open();
using (SqlTransaction tran = conn.BeginTransaction())
{
SqlCommand cmd1 = conn.CreateCommand();
cmd1.Transaction = tran;
cmd1.CommandText = cmdText1;
using (SqlDataReader reader1 = cmd1.ExecuteReader())
{
SqlCommand cmd2 = conn.CreateCommand();
cmd2.Transaction = tran;
cmd2.CommandText = cmdText2;
using (SqlDataReader reader2 = cmd2.ExecuteReader())
{
int actualOrderCount = 0;
while (reader1.Read())
{
Assert.True(actualOrderCount <= expectedOrders.Length, "FAILED: Received more results than expected");
DataTestUtility.AssertEqualsWithDescription(expectedOrders[actualOrderCount], reader1.GetValue(0), "FAILED: Received wrong value in order query at row " + actualOrderCount);
actualOrderCount++;
}
reader1.NextResult();
reader1.Read();
int customerCount = (int)reader1.GetValue(0);
int actualCustomerCount = 0;
while (reader2.Read())
{
Assert.True(actualCustomerCount <= expectedCustomers.Length, "FAILED: Received more results than expected");
DataTestUtility.AssertEqualsWithDescription(expectedCustomers[actualCustomerCount], reader2.GetValue(0), "FAILED: Received wrong value in customer query at row " + actualCustomerCount);
actualCustomerCount++;
}
reader2.NextResult();
reader2.Read();
int orderCount = (int)reader2.GetValue(0);
DataTestUtility.AssertEqualsWithDescription(expectedCustomers.Length, customerCount, "FAILED: Count query returned incorrect Customer count");
DataTestUtility.AssertEqualsWithDescription(expectedOrders.Length, orderCount, "FAILED: Count query returned incorrect Order count");
}
}
cmd1.CommandText = "select @@trancount";
int tranCount = (int)cmd1.ExecuteScalar();
Assert.True(tranCount == 1, "FAILED: Expected a transaction count of 1, but actually received " + tranCount);
tran.Commit();
}
}
}
示例12: XmlTest
public static void XmlTest()
{
string tempTable = "xml_" + Guid.NewGuid().ToString().Replace('-', '_');
string initStr = "create table " + tempTable + " (xml_col XML)";
string insertNormStr = "INSERT " + tempTable + " VALUES('<doc>Hello World</doc>')";
string insertParamStr = "INSERT " + tempTable + " VALUES(@x)";
string queryStr = "select * from " + tempTable;
using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = initStr;
cmd.ExecuteNonQuery();
try
{
cmd.CommandText = insertNormStr;
cmd.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand(insertParamStr, conn);
cmd2.Parameters.Add("@x", SqlDbType.Xml);
XmlReader xr = XmlReader.Create("data.xml");
cmd2.Parameters[0].Value = new SqlXml(xr);
cmd2.ExecuteNonQuery();
cmd.CommandText = queryStr;
using (SqlDataReader reader = cmd.ExecuteReader())
{
int currentValue = 0;
string[] expectedValues =
{
"<doc>Hello World</doc>",
"<NewDataSet><builtinCLRtypes><colsbyte>1</colsbyte><colbyte>2</colbyte><colint16>-20</colint16><coluint16>40</coluint16><colint32>-300</colint32><coluint32>300</coluint32><colint64>-4000</colint64><coluint64>4000</coluint64><coldecimal>50000.01</coldecimal><coldouble>600000.987</coldouble><colsingle>70000.9</colsingle><colstring>string variable</colstring><colboolean>true</colboolean><coltimespan>P10675199DT2H48M5.4775807S</coltimespan><coldatetime>9999-12-30T23:59:59.9999999-08:00</coldatetime><colGuid>00000001-0002-0003-0405-060708010101</colGuid><colbyteArray>AQIDBAUGBwgJCgsMDQ4PEA==</colbyteArray><colUri>http://www.abc.com/</colUri><colobjectsbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"byte\">1</colobjectsbyte><colobjectbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedByte\">2</colobjectbyte><colobjectint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"short\">-20</colobjectint16><colobjectuint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedShort\">40</colobjectuint16><colobjectint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"int\">-300</colobjectint32><colobjectuint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedInt\">300</colobjectuint32><colobjectint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"long\">-4000</colobjectint64><colobjectuint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedLong\">4000</colobjectuint64><colobjectdecimal xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"decimal\">50000.01</colobjectdecimal><colobjectdouble xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"double\">600000.987</colobjectdouble><colobjectsingle xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"float\">70000.9</colobjectsingle><colobjectstring xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"string\">string variable</colobjectstring><colobjectboolean xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"boolean\">true</colobjectboolean><colobjecttimespan xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"duration\">P10675199DT2H48M5.4775807S</colobjecttimespan><colobjectdatetime xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"dateTime\">9999-12-30T23:59:59.9999999-08:00</colobjectdatetime><colobjectguid xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" msdata:InstanceType=\"System.Guid\">00000001-0002-0003-0405-060708010101</colobjectguid><colobjectbytearray xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"base64Binary\">AQIDBAUGBwgJCgsMDQ4PEA==</colobjectbytearray><colobjectUri xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"anyURI\">http://www.abc.com/</colobjectUri></builtinCLRtypes><builtinCLRtypes><colbyte>2</colbyte><colint16>-20</colint16><colint32>-300</colint32><coluint32>300</coluint32><coluint64>4000</coluint64><coldecimal>50000.01</coldecimal><coldouble>600000.987</coldouble><colsingle>70000.9</colsingle><colboolean>true</colboolean><colobjectsbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"byte\">11</colobjectsbyte><colobjectbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedByte\">22</colobjectbyte><colobjectint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"short\">-200</colobjectint16><colobjectuint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedShort\">400</colobjectuint16><colobjectint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"int\">-3000</colobjectint32><colobjectuint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedInt\">3000</colobjectuint32><colobjectint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"long\">-40000</colobjectint64><colobjectuint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedLong\">40000</colobjectuint64><colobjectdecimal xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"decimal\">500000.01</colobjectdecimal><colobjectdouble xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"double\">6000000.987</colobjectdouble><colobjectsingle xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"float\">700000.9</colobjectsingle><colobjectstring xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"string\">string variable 2</colobjectstring><colobjectboolean xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"boolean\">false</colobjectboolean><colobjecttimespan xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"duration\">-P10675199DT2H48M5.4775808S</colobjecttimespan><colobjectdatetime xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"dateTime\">0001-01-01T00:00:00.0000000-08:00</colobjectdatetime><colobjectguid xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" msdata:InstanceType=\"System.Guid\">00000002-0001-0001-0807-060504030201</colobjectguid><colobjectbytearray xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"base64Binary\">EA8ODQwLCgkIBwYFBAMCAQ==</colobjectbytearray></builtinCLRtypes></NewDataSet>"
};
while (reader.Read())
{
Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected");
SqlXml sx = reader.GetSqlXml(0);
xr = sx.CreateReader();
xr.Read();
DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], xr.ReadOuterXml(), "FAILED: Did not receive expected data");
}
}
}
finally
{
cmd.CommandText = "drop table " + tempTable;
cmd.ExecuteNonQuery();
}
}
}
示例13: ExecuteReader
//for select statements using datareader
public static SqlDataReader ExecuteReader(string SelectStatement)
{
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
SqlCommand com = new SqlCommand(SelectStatement, con);
SqlDataReader dr = com.ExecuteReader();
return dr;
}
示例14: OpenGoodConnection
private static void OpenGoodConnection(string connectionString)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
DataTestClass.AssertEqualsWithDescription(ConnectionState.Open, conn.State, "FAILED: Connection should be in open state");
}
}
示例15: GetFloat
//use for getting a single float data
public static float GetFloat(string SelectStatement)
{
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
SqlCommand com = new SqlCommand(SelectStatement, con);
float id = Convert.ToInt32(com.ExecuteScalar());
con.Close();
return id;
}