我将图片路径插入数据库,当我得到路径时,我会用img
标签显示它们。
我可以做到,但我找不到我在sql查询后编写的方法。
我在sql查询后要写什么?
在Page_Load
我的选择命令有效。
c = new Common(ConfigurationManager.ConnectionStrings["ahapp"]);
string sql = "select Query";
string str = "";
DataTable dt = c.GetDataTable(sql);
foreach (DataRow item in dt.Rows)
{
str += "<img src='" + item["path"].ToString() + "' style='width:100px' />";
}
dokList.InnerHtml = str;
此代码总是说:
sql ="INSERT INTO DR_OZLUK VALUES(3," + ddlDoktor.SelectedValue + "," + belgeid + ",3," + str + ",1)";
SqlCommand cmd = new SqlCommand(sql, c);
cmd.ExecuteNonQuery();
答案 0 :(得分:2)
您的c
对象似乎是除SqlConnection类型之外的其他对象。普通班是什么? SqlCommand
有两个参数。第一个是string,它是sql语句或存储过程的名称,另一个参数是SqlConnection类型的对象。
答案 1 :(得分:2)
insert语句易受sql注入攻击,但问题与sql语句无关。问题是您在Common
异议中传递Connection
类而不是SqlCommand
对象。
试试这段代码:
string connStr = "connection string here";
string sqlStatement = "INSERT INTO DR_OZLUK VALUES (3, @val1, @val2, 3, @val3, 1)";
using (SqlConnection conn = new SqlConnection(connStr))
{
using(SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = sqlStatement;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("@val1", ddlDoktor.SelectedValue);
comm.Parameters.AddWithValue("@val2", belgeid);
comm.Parameters.AddWithValue("@val3", str);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}
正确编码
using
语句进行propr对象处理try-catch
块来正确处理对象答案 2 :(得分:0)
我认为c应该是连接对象
c = new Common
你正在传递c in connection of connection object。
创建对象的SQLCommand签名是
public SqlCommand(
string cmdText,
SqlConnection connection
)
所以根据它你的第二个参数必须是连接对象。这就是它给你一个错误的原因。您正在传递Common类对象以创建命令对象。通过MSDN链接获取更多信息:http://msdn.microsoft.com/en-us/library/877h0y3a.aspx
答案 3 :(得分:0)
您的c不是SqlConnection
,或者您的IDE有另一个错误与您粘贴的错误混淆。有时VS2010在显示错误时会被破坏。
答案 4 :(得分:0)
Or try this, this sample code is very secure and 100% works any time, you can copy paste it but u must put your connection string and table
string connectionStr = "connection string STRING";
string sqlQuery = "INSERT INTO yourtable VALUES (ID, @pam1, @pam2)";
///// Go to Base and execute Query but with trycatch because if you have problem with using connection it will tell you
try{
using (SqlConnection conn = new SqlConnection(connStr))
{
using(SqlCommand komand = new SqlCommand(conn,sqlQuery)) //command to use connection and Sqlquery
string fromcontrol = "test"; //this is string just for test
komand.Parameters.AddWithValue("@pam1", fromcontrol.ToString());
komand.Parameters.AddWithValue("@val2", fromcontrol.ToString());
conn.Open();
komand.ExecuteNonQuery();
}
catch(SqlException e)
{
//throw your execption to javascript or response; e.Message.ToString() + "SQL connection or query error";
}
catch(Exception ex)
{
//throw your execption to javascript or response; e.Message.ToString()+ "system error";
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
答案 5 :(得分:0)
谢谢大家。我找到了解决方案。我添加了这段代码c.GetExecuteNonQuery(sql);
并将其设为c global。