mysql jdbc demo_executeQuery

package cn.sva.re.dbconnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class connectionDB {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
// mysql的加载JDBC驱动程序
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("驱动加载错误");
e.printStackTrace();
}
// 与mysql数据库建立连接
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/song", "root", "song");
} catch (SQLException e) {
System.out.println("数据库链接错误");
e.printStackTrace();
}
// 创建Statement
try {
st = conn.createStatement();
// 创建一个JDBC声明
String objStr="手工";
String objNum="20";
String query="SELECT * FROM ov WHERE Product_ctg='"+objStr+"' LIMIT 1,"+objNum;
// select statement
rs = st.executeQuery(query);
int i=0;
while (rs.next()) {
// System.out.println("name"+rs.getString("Product_name"));
// String name=rs.getString(1); //获得数据库第一列
// String sex=rs.getString(2);
// System.out.println("姓名:"+name+"性别:"+sex); //输出信息
i++;

}
System.out.println("i="+i);
} catch (SQLException e1) {
System.out.println("数据操作错误");
e1.printStackTrace();
}
// 关闭数据库
try {
if (rs != null) {
rs.close();
rs = null;
}
if (st != null) {
st.close();
st = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
System.out.println("数据库关闭错误");
e.printStackTrace();
}
}
}

你可能感兴趣的:(java,sql,mysql,jdbc)