写出的第一个java连接MySQL的代码

import java.sql.*;
public class Test {
	
	 private static final String URL="jdbc:mysql://localhost:3306/test1?";//数据库连接字符串,这里的deom为数据库名
     private static final String NAME="root";//登录名
     private static final String PASSWORD="123456789";//密码
	 public static void main(String[] args) {
		// TODO Auto-generated method stub
          Connection  con = null;
          Statement sql;
          ResultSet rs;
         
          try {
        	  Class.forName("com.mysql.jdbc.Driver");
          }
          catch(Exception e) {
        		System.out.println("未能成功加载驱动程序,请检查是否导入驱动程序!");
                //添加一个println,如果加载驱动异常,检查是否添加驱动,或者添加驱动字符串是否错误
	       e.printStackTrace();
          }
          try {
        	  con=DriverManager.getConnection(URL,NAME,PASSWORD);
        	  System.out.println("获取数据库连接成功!");
          }
          catch(SQLException e) {
        		System.out.println("获取数据库连接失败!");
                //添加一个println,如果连接失败,检查连接字符串或者登录名以及密码是否错误
	       e.printStackTrace();
          }
           try { 
        	   sql=con.createStatement();
        	   rs=sql.executeQuery("select * from  mess");
        	   while(rs.next()) {
        		   String number=rs.getString(1);
        		   String name = rs.getString(2);
        		   Date date = rs.getDate(3);
        		   float height = rs.getFloat(4);
        	       System.out.printf("%s\t",number);
        	       System.out.printf("%s\t",name);
        	       System.out.printf("%s\t",date);
        	       System.out.printf("%.2f\n",height);
        	   }
        	   con.close();
        	  
           }
           catch(SQLException e) {
        	   System.out.println(e);
           }
         
	}

}

SQL语句:

CREATE TABLE `mess` (
  `number` char(50) NOT NULL,
  `name` varchar(100) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  `height` float DEFAULT NULL,
  PRIMARY KEY (`number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

总结:在使用异常处理语句的时候,加上一些输出,可以方便判断是否进行到这一步

猜你喜欢

转载自blog.csdn.net/deepseazbw/article/details/80218256