在此代码中,我必须在数据库中添加数据,没有错误,但是数据未添加到数据库中. [英] In this code I have to add data in my database there is no error but data is not added in the database.
问题描述
尝试
{
字符串 connectionString =
" +
" ;
使用(SqlConnection conn =
新 SqlConnection(connectionString))
{
conn.Open();
使用(SqlCommand cmd =
新 SqlCommand(" " ,conn))
{
cmd.Parameters.AddWithValue(" , 5 );
cmd.Parameters.AddWithValue(" ," Amal Hashim");
cmd.Parameters.AddWithValue(" ," 班加罗尔");
cmd.Parameters.AddWithValue(" , 007 );
cmd.Parameters.AddWithValue(" ," 管理器");
int 行= cmd.ExecuteNonQuery();
Console.WriteLine(" );
// 行插入的记录数
}
}
}
捕获(SqlException ex)
{
Console.WriteLine(" );
}
我尝试过的事情:
尝试使用控制台应用程序在数据库中添加数据.
我认为您的连接字符串编写不正确.
应该是:
<br /> connetionString="Data Source=YourServerName;<br /> Initial Catalog=YourDatabaseName; User ID=UserName;Password=Password"
如果您使用的是Windows身份验证,则只需删除用户ID和密码并添加Integrated Security=True
您可以通过下面的链接获取更多详细信息:
C#SQL Server连接 [try { string connectionString = "server=((localdb)-MSSQLLocalDB);" + "initial catalog=Employee;"; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand("INSERT INTO Employee VALUES(" + "@EmpId, @EmpName, @EmpAddress,@EmpCode,@EmpDesig)", conn)) { cmd.Parameters.AddWithValue("@EmpId", 5); cmd.Parameters.AddWithValue("@EmpName", "Amal Hashim"); cmd.Parameters.AddWithValue("@EmpAddress", "Bangalore"); cmd.Parameters.AddWithValue("@EmpCode", 007); cmd.Parameters.AddWithValue("@EmpDesig", "Manager"); int rows = cmd.ExecuteNonQuery(); Console.WriteLine("you are here"); //rows number of record got inserted } } } catch (SqlException ex) { Console.WriteLine("Try block is failed"); }
What I have tried:
Try to add a data in database using console application.解决方案I think your connection string is not written properly.
It should be :
<br /> connetionString="Data Source=YourServerName;<br /> Initial Catalog=YourDatabaseName; User ID=UserName;Password=Password"
Incase you are using Windows Authentication you just have to remove User Id and Password and addIntegrated Security=True
You can go through below link for more detail :
C# SQL Server Connection[^]
这篇关于在此代码中,我必须在数据库中添加数据,没有错误,但是数据未添加到数据库中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!