import java.sql.DriverManager
import java.sql.ResultSet
import java.sql.ResultSetMetaData
import java.sql.Statement
import java.util.Hashtable
public class GetDBFiled {
public static void conn() {
String driver = "com.mysql.jdbc.Driver"
String url = "jdbc:mysql://localhost:3306/databaseName"
String user = "root"
String password = "密码"
try {
Class.forName(driver)
Connection conn = DriverManager.getConnection(url, user, password)
if (!conn.isClosed()) {
String sql = "select * from pic"
System.out.println("Succeeded connecting to the Database!")
Statement statement =conn.createStatement()
ResultSet rs = statement.executeQuery(sql)
if (rs.next()) {
// 得到ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData()
System.out.println(rsmd.getColumnCount())
for (int i = 1 i <= rsmd.getColumnCount() i++) {
Hashtable hst = new Hashtable()
// 把字段名放入Name
String name = String.valueOf(rsmd.getColumnLabel(i))
hst.put("Name", name)
// 把字段类型放入Type
String type = String.valueOf(rsmd.getColumnType(i))
hst.put("Type", type)
System.out.println(hst.get("Name")+" "+hst.get("Type"))
}
}
}
} catch (Exception e) {
System.out.println("出现异常")
}
}
}
用JDBC连接数据库,然后用sql语句。要导入mysql的驱动包。import java.sql.*
public class TestMySql {
static Connection con = null// 声明Connection对象
static Statement sql = null
static ResultSet res = null
public static void main(String[] args) {
TestMySql c = new TestMySql()
con = c.getConnection()
try {
sql = con.createStatement()
res = sql.executeQuery("select * from dept")
//sql语句,我数据库里有张dept表
while (res.next()) {//输出结果
System.out.print(res.getString(1) + "<——>")
System.out.print(res.getString(2) + "<——>")
System.out.print(res.getString(3) )
System.out.println()
}
} catch (SQLException e) {
e.printStackTrace()
} finally {
try {
if (res != null) {
res.close()
res =null
}
if (sql != null) {
sql.close()
sql =null
}
if (con != null) {
con.close()
con =null
}
} catch (SQLException e) {
e.printStackTrace()
}
}
}
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver")
// 加载oracleJDBC驱动
System.out.println("数据库驱动加载成功")
} catch (ClassNotFoundException e) {
e.printStackTrace()
}
try {// 通过访问数据库的URL获取数据库连接对象
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydata", "root", "qwer1234")
//mydata为mysql名字
System.out.println("数据库连接成功")
} catch (SQLException e) {
e.printStackTrace()
}
return con// 按方法要求返回一个Connection对象
}
}
不建议这样做,一般不符合开发规范,如果这样的话,你想想在业务量多的情况下,多个线程如果不控制,数据库连接会将数据库服务器爆掉的,会影响业务的常规做法:数据库连接池(durid了解一下),据某些统计哈,真正用来做查询的资源不超过整个查询数据库的生命周期的30%,大部分时间都用开创建连接关闭连接等 *** 作,如果这个时候建立数据库连接池的话,可以有效的将这部分时间释放掉
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)