我正在尝试将三个变量写入数据库表。我的代码是:
sqlCmd.CommandText = "INSERT INTO dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES(StudentNumber.ToString() , Time.ToString() , Total.ToString())" + dbConnection;
sqlCmd.ExecuteNonQuery();
sqlTran.Commit();
dbconnection是连接的名称。它没有做任何事情。这是一个尝试捕获,但直接赶上。 提前谢谢。
答案 0 :(得分:2)
你应该
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
}
}
答案 1 :(得分:0)
StudentNumber.ToString()
无法包含在查询中!这是java代码而不是sql ...
答案 2 :(得分:0)
//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);
答案 3 :(得分:-2)
你想要这样的东西:
sqlCmd.CommandText = "INSERT INTO
dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES ('" +
StudentNumber.ToString() + "'," + Time.ToString() + "," + Total.ToString() + ")";