尝试为文件abc附加自动命名的数据库失败 [英] An attempt to attach an auto-named database for file abc failed

查看:52
本文介绍了尝试为文件abc附加自动命名的数据库失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误消息尝试为文件abc附加自动命名的数据库失败.存在具有相同名称的数据库,或者无法打开指定的文件,或者该文件位于UNC共享上"

I get the error "An attempt to attach an auto-named database for file abc failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share"

private void btnsubmit_Click(object sender, EventArgs e)
        {
           
            String connectionString = "Data Source=USER\\SQLEXPRESS;Integrated Security=true; AttachDbFilename=abc;User Instance=true;";
            SqlConnection thisConnection = new SqlConnection(connectionString);
         
            

            thisConnection.Open();

            String thisQuery = "INSERT INTO abc (ID, Name, ContactNo, Email, Address) VALUES (''" + txtid.Text + "'', ''" + txtname.Text + "'', ''" + txtcontact.Text + "'', ''" + txtemail.Text + "'', ''" + txtaddress.Text + "'')";
            SqlCommand thisCommand = new SqlCommand(thisQuery, thisConnection);
            SqlCommand cmd = new SqlCommand();

            thisCommand.ExecuteNonQuery();
            thisConnection.Close();

        }

推荐答案

您尚未指定任何错误,但我认为由于查询而出现错误

您在数据库中的ID列是整数类型,并且您像字符串
一样发送它 像这样==>
更改它
You haven''t specified any error but i think you are getting error because of query

your ID column in DB is of integer type and you are sending it like string
Change it like this ==>
String thisQuery = "INSERT INTO abc (ID, Name, ContactNo, Email, Address) VALUES (" + txtid.Text + ", '" + txtname.Text + "', '" + txtcontact.Text + "', '" + txtemail.Text + "', '" + txtaddress.Text + "')";


或者,如果您的ID列是身份(即自动递增字段),则无需在查询中发送它


Or if your ID column is identity(ie autoincrement field) then no need to send it in query

String thisQuery = "INSERT INTO abc ( Name, ContactNo, Email, Address) VALUES ('" + txtname.Text + "', '" + txtcontact.Text + "', '" + txtemail.Text + "', '" + txtaddress.Text + "')";



这样发送参数以进行查询不是一个好习惯,因为会有更多的sql注入机会,所以您应该始终使用SQL参数发送以进行查询



This is not a good practice to send parameters to query like this way as there''ll be a greater chance of sql injection so yo should always use SQL Parameters to send to query


我认为数据库连接中的代码错误没有错误,您可以将错误消息发送给我吗?
i think problem in your data base connection in code no error can you send the error message to me


将数据库文件保留在部署文件夹中.在您的连接字符串中,只需添加"database = abc".这会阻止SQL Server创建自动命名的数据库
keep the database file in deployment folder. and In you connection string just add the ''database=abc''. This prevents SQL server to create the auto-named database


这篇关于尝试为文件abc附加自动命名的数据库失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆