如果用户名不存在“INSERT INTO”Else“UPDATE”(显示信息)

时间:2015-07-20 14:37:56

标签: c# ms-access asp-classic

这是我的表:

<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>

我希望验证 IF 用户名存在于数据库中,向我显示更新 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;
        }
    }
}

我的目的是之前回答我的表显示已回答的问题[或显示“用户已经回答”的消息]如果我的数据库中不存在则显示表格到现场。 这让我疯狂不能这样的事情

1 个答案:

答案 0 :(得分:0)

这可以像这样实现,

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          
}

编辑@ Aツ

指出的代码