如何仅从Java-MySQL中的表中获取单个结果?
让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(101,'Chris'); mysql> insert into DemoTable values(102,'David'); mysql> insert into DemoTable values(103,'Mike');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable;
这将产生以下输出-
+------+-------+ | Id | Name | +------+-------+ | 101 | Chris | | 102 | David | | 103 | Mike | +------+-------+ 3 rows in set (0.00 sec)
现在让我们看一下Java-MySQL代码。这将仅从表顶部获取一条记录-
示例
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import com.mysql.jdbc.ResultSetMetaData; public class OneResultDemo { public static void main(String[] args) { Connection con = null; PreparedStatement ps = null; Statement st = null; ResultSet rs = null; try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/web?useSSL=false", "root", "123456"); String query = "select *from DemoTable " + " limit 1"; st = con.createStatement(); rs = st.executeQuery(query); while (rs.next()) { System.out.println("Id=" + rs.getInt("Id")); System.out.println("Name=" + rs.getString("Name")); } } catch (Exception e) { e.printStackTrace(); } } }
输出结果
这将产生以下输出-
Id=101 Name=Chris