我需要输出仅在第一行的数据,但它正在打印添加到数据库表中的所有数据。这是数据:
例如,它应该只打印“Not Very Nice”和 ID 为 27 的消息,而不是 ID 为 28 的第二行。
代码如下:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class feedback1 : System.Web.UI.Page
{
SqlConnection con;
string cons = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(cons);
con.Open();
cmd = new SqlCommand("insert into feedback(username,message) values('" + TextBox1.Text + "','" + TextBox2.Text +"')", con);
cmd.ExecuteNonQuery();
}
}
这是输出页面代码..
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1" EnableModelValidation="True" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" GridLines="None">
<Columns>
<asp:BoundField DataField="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="username" HeaderText="username" SortExpression="username" />
<asp:BoundField DataField="message" HeaderText="message" SortExpression="message" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" OnSelecting="SqlDataSource1_Selecting" SelectCommand="SELECT * FROM [feedback]"></asp:SqlDataSource>
<div>
</div>
</form>
最佳答案
这只是修改 SQL 查询的一个例子:
选择第一行:
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
OnSelecting="SqlDataSource1_Selecting"
SelectCommand="SELECT * FROM [feedback] LIMIT 1">
</asp:SqlDataSource>
选择特定的 ID:
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
OnSelecting="SqlDataSource1_Selecting"
SelectCommand="SELECT * FROM [feedback] WHERE [id] = REPLACE_WITH_YOUR_NUMBER">
</asp:SqlDataSource>
"Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a limited number of records."
请参阅:https://www.w3schools.com/sql/sql_top.asp
注意
您的程序容易受到 SQL 注入(inject)攻击。 请修改您的输入以在执行之前清理您的查询。protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(cons);
con.Open();
string txtb1= TextBox1.Text,
txtb2= TextBox2.Text;
sqlCommand.CommandText = "select * from product where name = @name";
cmd = new SqlCommand("insert into feedback(username,message) values('" + @txtb1 + "','" + @txtb2 +"')", con);
cmd.Parameters.AddWithValue("txtb1", txtb1);
cmd.Parameters.AddWithValue("txtb2", txtb2);
cmd.ExecuteNonQuery();
}
😠停在那里! 🚨✋!我是警察👮希望你知道read up on the laws在这个街区附近。您违反了刑法 404 - 未找到数据库!
如果你在这个社区再次发帖 📖 sql-vulnerable 📠 🏠🏠
我将不得不🔒逮捕你🔒
今天没票👦
📟这只是警告⚠️下次小心🚧
关于c# - 只打印数据库第一行的数据而不是整个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54143274/