将值写入sql数据库
问题描述:
我想写入三个变量到数据库表中。我的代码是:将值写入sql数据库
sqlCmd.CommandText = "INSERT INTO dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES(StudentNumber.ToString() , Time.ToString() , Total.ToString())" + dbConnection;
sqlCmd.ExecuteNonQuery();
sqlTran.Commit();
dbconnection是连接的名称。它什么都不做。这是一个尝试赶上,但直接赶上。 在此先感谢。
答
你应该
- 避免连接在一起,你的SQL语句 - 避免SQL注入攻击!改用参数化查询!
- 您
SqlConnection
和SqlCommand
对象
使用用块尝试是这样的:
string _connString = "........";
string queryStmt =
"INSERT INTO dbo.PortfolioValues(StudentNumber, TimeStamp, PortfolioValue) " +
"VALUES(@StudentNumber, @TimeStamp, @TotalValue)";
using(SqlConnection _con = new SqlConnection(_connString))
using(SqlCommad _cmd = new SQlCommand(queryStmt, _con))
{
// create paramters and set values
_cmd.Parameters.Add("@StudentNumber", SqlDbType.Int).Value = StudentNumber;
// do the same for the other two parameters
try
{
_con.Open();
_cmd.ExecuteNonQuery();
_con.Close();
}
catch(Exception exc)
{
// handle exception
}
}
答
你想是这样的:
sqlCmd.CommandText = "INSERT INTO
dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES ('" +
StudentNumber.ToString() + "'," + Time.ToString() + "," + Total.ToString() + ")";
+0
虽然这会起作用,但它是一个sql注入攻击的教科书案例 – 2011-05-03 14:26:39
+0
@Jim那么,这取决于其余的代码。 – 2011-05-03 14:27:13
答
StudentNumber.ToString()
不能包含在查询!它的Java代码不是SQL ...
答
//Am asuming you are using C# and the System.Data.SqlClient
//here is how you might do what you want
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
//so that you use it this way:
String query = String.Formart("INSERT INTO dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES(\"{0}\",\"{1}\",\"{2}\")",StudentNumber.ToString() , Time.ToString() , Total.ToString());
String connectionString = "your connection string";
CreateCommand(query,connectionString);
** **什么异常,你从catch块得到???另外:你能否在这里发布**完整的**源代码 - 你依赖于连接和交易,但你永远不会显示这些是如何创建的...... – 2011-05-03 14:20:59
你使用的是什么RDBMS? – datagod 2011-05-03 14:23:28