[英]App.startup path does not work in my visual studio project?
There is no error in this code but when i insert the values,they are not actually inserted in database. 这段代码没有错误,但是当我插入值时,它们实际上并没有插入数据库中。 Here is my connection string class :
这是我的连接字符串类:
public class DBConn
{
public static SqlConnection GetConnection()
{
string sDBPath = Application.StartupPath + @"\App_Data\Database3.mdf";
string connStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename='" + sDBPath + "';Integrated Security=True;User Instance=True";
return new SqlConnection(connStr);
}
}
and in this class i call the connection string class : 在这个类中,我将连接字符串类称为:
string query = "INSERT INTO Table1 VALUES('" + textBox1.Text + "')";
SqlConnection con = DBConn.GetConnection();
SqlCommand com = new SqlCommand(query,con);
con.Open();
using (con)
{
com.ExecuteNonQuery();
MessageBox.Show("Insert");
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
Your use of the using
statement is not recommended and leads to 不建议您使用
using
语句,这会导致
problems. 问题。 You have to instantiate the resource object inside the
您必须实例化内部的资源对象
using
statement! using
声明! It's scope or lifetime is now limited to the 现在它的范围或生存期仅限于
statement block and will be properly garbage collected. 语句块,将被正确地垃圾回收。 The way you
你的方式
use it (by passing an already instantiated object into the using
使用它(通过将已经实例化的对象传递给
using
statement) the objects remains valid although not properly accessible since it was never properly closed or disposed. 语句)对象仍然有效,尽管由于从未正确关闭或处置对象而无法正确访问。 MSDN - using statement .
MSDN-using语句 。 So instead of creating the connection and passing it around your application (bad practice) you should create the connection settings (connection string) and the query and use them to create a connection resource inside a using statement everytime you need a connection.
因此,应该创建连接设置(连接字符串)和查询,并在每次需要连接时使用using语句内的连接资源来创建连接设置(连接字符串)和查询,而不是创建连接并在应用程序中传递连接。 This way the resource is always correctly disposed.
这样,资源总是可以正确处理。 The provided link gives you an example how to use a using statement.
提供的链接为您提供了一个如何使用using语句的示例。
Check your connection string well if all provided information is valid or all needed information is provided (eg username and password). 如果提供的所有信息均有效或提供了所有必需的信息(例如,用户名和密码),请仔细检查您的连接字符串。
Check database settings (eg permissions) 检查数据库设置(例如权限)
SqlConnection
class has an event called InfoMessage
. SqlConnection
类具有一个名为InfoMessage
的事件。 In case the connection produces any warnings or errors you will get notified. 如果连接产生任何警告或错误,您将得到通知。
Check your database (eg log) for the occurance of errors. 检查您的数据库(例如日志)是否出现错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.