如果不存在用户名“INSERT INTO”其他“UPDATE”(显示信息)(If username

2019-10-24 00:48发布

这是我的表:

<table>
    <tr><td><b>Utilizador:</b></td><td><asp:Label ID="username" runat="server"></asp:Label></td></tr> 
    <tr><td><b>Telefone da Empresa:</b></td><td><asp:TextBox ID="empresa" runat="server" MaxLength="13"></asp:TextBox> (Exemplo: +351234925xxx)</td></tr>
    <tr><td><b>2º Telefone:</b></td><td><asp:TextBox ID="empresa2" runat="server" MaxLength="4"></asp:TextBox> (Exemplo: xxxx)</td></tr>
    <tr><td><b>Telemóvel:</b></td><td><asp:TextBox ID="telemovel" runat="server" MaxLength="13"></asp:TextBox> (Exemplo: +3519xxxxxxxx)</td></tr>
    <tr><td colspan="2"><asp:Label ID="lblInfo" runat="server" Font-Bold="True"></asp:Label></td></tr>
    <tr><td><asp:Button ID="cmdSave" runat="server" Text="Guardar" onclick="cmdSave_Click" /></td><td></td></tr>
</table>

我想验证是否在用户名数据库中告诉我的答案更新 ELSE 插入

这是我后面的代码至今。 它插入到

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        username.Text = "[" + HttpContext.Current.User.Identity.Name + "]"; 
    }

    protected void cmdSave_Click(object sender, EventArgs e)
    {
        string sFilePath = Server.MapPath("Database3.accdb");
        OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFilePath + ";Persist Security Info=False;");
        string insertCmd = "INSERT INTO colaborador(Empresa,Empresa2,Telemovel,username) VALUES (@Empresa,@Empresa2,@Telemovel,@username)";
        using (Conn)
        {
            Conn.Open();
            OleDbCommand myCommand = new OleDbCommand(insertCmd, Conn);
            myCommand.Parameters.AddWithValue("@Empresa", empresa.Text);
            myCommand.Parameters.AddWithValue("@Empresa2", empresa2.Text);
            myCommand.Parameters.AddWithValue("@Telemovel", telemovel.Text);
            myCommand.Parameters.AddWithValue("@username", HttpContext.Current.User.Identity.Name);            
            Response.Write(" ");
            myCommand.ExecuteNonQuery(); 
            lblInfo.Text = "Dados guardados!";
            lblInfo.ForeColor = System.Drawing.Color.Green;
        }
    }
}

我的目的是回答问题前,我的表显示已回答的问题[或显示信息:“用户已经回答”如果在我的数据库不存在则显示该表中字段。 它的驾驶我疯狂不能这样的事情

Answer 1:

这可以这样来实现,

SqlCommand objcmd = new SqlCommand("SELECT 1 from Table WHERE Username=@NAME" , objsqlconn);//get rows if username exists
cmd.Parameters.Add("@NAME", SqlDbType.NVarChar,20).Value = Master_product_txt.Text;   
objsqlconn.Open();
readr = SelectCommand.ExecuteReader();

if (!readr.HasRows) 
{
`// write Code to insert values
}`
else
{
    //write code to retrieve values and update          
}

编辑由@一ツ指出码



文章来源: If username not exist “INSERT INTO” Else “UPDATE” (display info)