public JSONObject getUser(String name) throws ClassNotFoundException{
JSONObject json = new JSONObject();
Connection conn = null;
// 1、加载驱动
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// 2、建立连接
try {
conn = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;databaseName=Commission",
"sa", "12344321");
System.out.println("建立连接成功!");
//建立Statement对象
Statement stmt=conn.createStatement();
String sql="select * from [Commission].[dbo].[user] where name = '" + name+"'";
ResultSet rs=stmt.executeQuery(sql);
//执行insert update delete等语句,先定义sql
// stmt.executeUpdate(sql);
while(rs.next())
{
json.put("id", rs.getObject(1));
json.put("name", rs.getObject(2));
json.put("password", rs.getObject(3));
// System.out.println("你的第一个字段内容为:"+rs.getString(1));
// System.out.println("你的第二个字段内容为:"+rs.getString(2));
// System.out.println("你的第二个字段内容为:"+rs.getString("password"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 3、关闭连接
try {
if (null != conn) {
conn.close();
System.out.println("关闭连接成功!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
最基本的java连接数据库
最新推荐文章于 2022-09-15 09:33:13 发布