I have a simple two-field form that stores its data in the database. For some reason, it isn't working. I have verified that the connection string works, as it is used in another pro开发者_StackOverflow社区ject I made.
I didn't include the beginning of the first class or its page load.
Code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string Name = txtName.Text;
string Description = txtSpecial.Text;
string method = string.Format(
"INSERT INTO RbSpecials (Name,Description,Active) VALUES ('{0}','{1}','1')",
Name,
Description);
RbConfiguration mySql = new RbConfiguration();
try
{
mySql.Sql_Connection(method);
}
catch
{
}
}
}
public class RbConfiguration
{
string DbConnectionString = "System.Configuration.ConfigurationManager.ConnectionStrings['RBConnectionString'].ConnectionString";
public void Sql_Connection(string queryString)
{
SqlConnection conn = new SqlConnection(DbConnectionString);
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
conn.Close();
}
}
You never execute your SQL command:
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
And your connection string is wrong (ditch the double quotes):
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
Well without knowing the error, I'll give it a shot anyway.
string DbConnectionString = "System.Configuration.ConfigurationManager.ConnectionStrings['RBConnectionString'].ConnectionString";
Should be
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
And as Adam says, you never actually execute your Query. The Sql_Connection-method, only opens a connection, and then closes it again, without actually doing anything.
Try this instead:
public void Sql_Connection(string queryString)
{
using( SqlConnection conn = new SqlConnection(DbConnectionString) )
{
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Check your connection string code must not be a string its class which is getting connection string from web.config, so it should be like this
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
You did not execute your SQlCommand, so will it insert the data, do this
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
its not the cause but the best practice to not to make your code vulnerable to SQLINjection, try this article
How To: Protect From SQL Injection in ASP.NET
精彩评论