通过JDBC从mysql获取单元格值

时间:2013-09-15 16:34:35

标签: java mysql jdbc

我的方法应该从username获得passwordadmintable

我在MySql控制台中的表:

enter image description here

我的方法:

    public void adminEnterCondition(){
    Connection con;
    PreparedStatement preparedStatement;
    ResultSet resultSet;
    String query = "select * from admintable";
    String username,password;
    try {
        con= DriverManager.getConnection(...);
        preparedStatement = con.prepareStatement(query);
        resultSet = preparedStatement.executeQuery();
        username = ... 
        password = ...

    }
    catch (SQLException sqle){
        sqle.printStackTrace();
    }
}

更新

我试试这个:

    public void adminEnterCondition() {
    Connection con;
    PreparedStatement preparedStatement;
    ResultSet resultSet;
    String query = "select * from admintable";
    String username = null, password = null;
    try {
        con = DriverManager.getConnection(...);
        System.out.println("Connected");
        preparedStatement = con.prepareStatement(query);
        resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            username = resultSet.getString(username);
            password = resultSet.getString(password);
        }

        System.out.println(username);
        System.out.println(password);

    } catch (SQLException sqle) {
        sqle.printStackTrace();
    }
}

但是会发生这种异常:

Connected
Exception in thread "main" java.lang.NullPointerException
at java.lang.String$CaseInsensitiveComparator.compare(String.java:1176)
at java.lang.String$CaseInsensitiveComparator.compare(String.java:1170)
at java.util.TreeMap.getEntryUsingComparator(TreeMap.java:369)
at java.util.TreeMap.getEntry(TreeMap.java:340)
at java.util.TreeMap.get(TreeMap.java:273)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1072)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5488)
at test.GetCellvalue.adminEnterCondition(GetCellvalue.java:26)
at test.GetCellvalue.main(GetCellvalue.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

2 个答案:

答案 0 :(得分:2)

使用这种方式检索

while(resultSet.next())
{
username=resultSet .getString("username");
password=resultSet .getString("password");
}

<强> OtherWay 您也可以像这样编写列号

,而不是写列名
while(resultSet.next())
    {
    username=resultSet .getString(1);
    password=resultSet .getString(2);
    }

答案 1 :(得分:1)

您可以通过列名从ResultSet中检索这些字符串:

    String username = resultSet.getString("username");
    String password = resultSet.getString("password");