插入数据库 [英] Insert into database

查看:132
本文介绍了插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我有一个系统来添加用户,我必须检查此用户是否存在以便我不会再次添加他,我将所有的名称从数据库检索到arraylist.I先检查是否数组列表是空的,以便我可以添加用户,他将检查他是否存在。
这里是代码

I have a problem, I have a system to add users, I have to make check if this user exist before so that i will not add him again, I retrieved all the name from database into an arraylist.I check first if the array list is empty so that I can add the user else he will check if he exists or not here is the code

    if(names.size() == 0){
        dbstatement.executeUpdate("
        insert into users (user_name,user_password,user_type) 
        values ('" + username + "','" + userpassword + "','" + type + "')");
        JOptionPane.showMessageDialog(rootPane, "user added successfully");
    }
    else{                   
        for (int i = 0; i < names.size(); i++) {
            if (username.equals(names.get(i))) {
                JOptionPane.showMessageDialog(rootPane, "Sorry, this name already exist");
                break;
            }
        }
        dbstatement.executeUpdate
        ("insert into users(user_name,user_password,user_type) 
        values ('" + username + "','" + userpassword + "','" + type + "')");
    }

问题是当程序发现名称存在之前他告诉我并添加他,我知道这个问题的原因所有我想知道在哪里,但如果在里面for循环,我希望他告诉我用户只存在不再添加它

the problem is when the program found a name exist before he told me and add him, i know the cause of this problem all i want to know where to but else of the if inside for loop, I want him to tell me the user exist onlyy not to add it again

推荐答案

只需使用要添加的每个名称调用数据库。

Just call the database with each name to add.

让sql尝试插入名称。它将插入或抛出密钥违规(假设您对名称有唯一约束)。

Let the sql try to insert the name. It will either insert or throw a key violation (assuming you have a unique constraint on the name).

如果它引发密钥违规,您就知道该名称已存在于数据库中。

If it throws a key violation you know the name is already in the database.

如果它没有抛出错误,则插入名称。

If it does not throw an error then the name was inserted.

读取/决定/写入样式处理不是让这项工作的方式。当另一个进程在读取和写入之间插入新名称时,它仍然会出现问题。这意味着您仍然必须检查密钥违规。如果你必须检查密钥违规,你也可以在第一时间做到正确,并尝试插入所有名称。

Read/decide/write style processing is not the way to make this work. It can still have issues when another process inserts a new name in the time between the read and the write. This means that you still have to check for key violations anyway. If you have to check for key violations anyway you might as well do it right the first time and just try inserting all the names.

这篇关于插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆