当前位置:Gxlcms > 数据库问题 > mysql jdbc连接

mysql jdbc连接

时间:2021-07-01 10:21:17 帮助过:3人阅读

  1. public class JDBCTest {
  2. public static void main(String[] args) {
  3. String sql = "SELECT * FROM usertest";
  4. Connection conn = null;
  5. Statement st = null;
  6. ResultSet rs = null;
  7. try {
  8. Class.forName("com.mysql.jdbc.Driver");
  9. conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wzz","root","1020");
  10. st = conn.createStatement();
  11. rs = st.executeQuery(sql);
  12. while(rs.next()){
  13. System.out.println(rs.getString("name")+rs.getInt("age"));
  14. }
  15. } catch (Exception e) {
  16. e.printStackTrace();
  17. }finally{
  18. try {
  19. rs.close();
  20. } catch (Exception e2) {
  21. }
  22. try {
  23. st.close();
  24. } catch (Exception e3) {
  25. }
  26. try {
  27. conn.close();
  28. } catch (Exception e4) {
  29. }
  30. }
  31. }
  32. }<br><br><br><br><br>
  1. public class JDBCTest {
  2. public static Connection getConnection() {
  3. Connection conn = null;
  4. try {
  5. Class.forName("com.mysql.jdbc.Driver");
  6. conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wzz","root","1020");
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }
  10. return conn;
  11. }
  12. public static void main(String[] args) {
  13. Connection conn = getConnection();
  14. Statement st = null;
  15. try {
  16. String sql="insert into usertest(name,age) values(‘abc‘,18)";
  17. st = conn.createStatement();
  18. int count = st.executeUpdate(sql);
  19. System.out.println(count);
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. }finally{
  23. try {
  24. st.close();
  25. } catch (Exception e1) {
  26. }
  27. try {
  28. conn.close();
  29. } catch (Exception e2) {
  30. }
  31. }
  32. }
  33. }

 

  

mysql jdbc连接

标签:

人气教程排行