且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#Winform应用程序SQL连接不起作用

更新时间:2023-10-14 09:37:16

在不知道错误消息的情况下,甚至很难猜测-这可能很简单,因为您输入的字段名称错误.
但是,请不要将字符串连接起来以形成SQL命令!它使您对意外或蓄意的SQL注入攻击敞开大门,这可能会破坏整个数据库.改用参数化查询:
Without knowing the error message it is difficult to even guess - it may be as simple as you have a field name wrong.
But please, please, please do not concatenate strings to form an SQL command! It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead:
string sqlInsert = @"INSERT INTO clients(Client, Contact, Address, Telephone, NumberOfJobs, LastJob)VALUES(@CL, @CN, @AD, @TN, @JC, @LJ)";

try
{
    conn.Open();
    SqlCommand cmd = new SqlCommand(sqlInsert);
    cmd.Parameters.AddWithValues("@CL", this.Client);
    cmd.Parameters.AddWithValues("@CN", this.Contact);
    cmd.Parameters.AddWithValues("@AD", this.Address);
    cmd.Parameters.AddWithValues("@TN", this.Telephone);
    cmd.Parameters.AddWithValues("@JC", this.NumberOfJobs);
    cmd.Parameters.AddWithValues("@LJ", this.LastJob);
    cmd.ExecuteNonQuery();

而且阅读起来容易得多!

And it is a lot easier to read!


检查您是否可以连接到SQL Server(Editor)实例-"localhost",方法是: Windows身份验证模式.

您可以参考以下链接,以获得有关SQL Server的不同类型的连接字符串的更多详细信息.

http://connectionstrings.com/sql-server

http://connectionstrings.com/sql-server-2005

http://connectionstrings.com/sql-server-2008
Check you are able to connect to your SQL Server(Editor) Instance - "localhost", by Windows-Authentication Mode.

You may refer below links for more details on different types of connection strings for SQL-Server.

http://connectionstrings.com/sql-server

http://connectionstrings.com/sql-server-2005

http://connectionstrings.com/sql-server-2008


您已设置所有的值都是字符串.这是正确的吗?

当然,您的代码看起来并不正确,但是问题可能出在您的数据上.您的数据是什么?例如,如果this.Contact 包含单引号...则您搞砸了SQL语句,因为它将认为字符串在此结束.您可以通过采用OriginalGriff的使用参数的建议来解决此问题,无论如何这都是一个好主意.

调试时,是否可以确认要在this.Contact等变量中正确设置了您要预期的数据?
You setup all of the values to be strings. Is this correct?

Of hand, your code doesn''t look incorrect, but the problem could be your data. What IS your data? If for example this.Contact contains a single quote...then you''ve messed up your SQL statement because it will think the string ends there. You can fix this by taking OriginalGriff''s suggestion of using parameters, which is just a good idea anyway.

When you debug, are you able to confirm that the data you''re anticipating is properly set in the variables like this.Contact, etc.?