Java Jdbc查询MySQL数据库示例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class MySQLTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null;
try
{
String userName = "username";
String password = "password";
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement pstmt;
ResultSet rset;
pstmt = conn.prepareStatement("select count(*) from testtable");
rset=pstmt.executeQuery();
while (rset.next()){
System.out.println (rset.getString(1)); // Print col 1
}
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
关注微信公众号福利!!!
回复关键字「666」获取一份最新 Java 架构资料,你要的都有!
回复关键字「Java」获取JVM, 多线程等Java技术系列教程;
回复关键字「spring」获取Spring, Spring Boot, Spring Cloud教程;
回复关键字「架构」获取分布式、微服务、架构、高并发等系列干货;
回复关键字「面试」获取各种 Java 面试题及答案、面试实战经验;