第一种:
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
String url = "jdbc:mysql://localhost:3306/admin";
//MySQL配置时的用户名
String user = "root";
//MySQL配置时的密码
String password = "";
Class.forName("com.mysql.jdbc.Driver");//动态加载驱动
con = (Connection) DriverManager.getConnection(url, user, password);
Statement statement = con.createStatement();
第二种
Class.forName("com.mysql.jdbc.Driver");//动态加载驱动
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/admin?user=root&password=");
Statement statement = con.createStatement();
两种几乎相同,只是DriverManager.getConnection(url)的方法不同
String sql = "SELECT * FROM admin WHERE NAME='"+username+"' AND pwd = '"+pwd+"'";
statement.execute(sql)
问题:
运行的时候碰到no suitable driver found for jdbc:mysql//localhost:3306/admin 异常
解决方法:没有加载驱动Class.forName("com.mysql.jdbc.Driver");
查到一些原因:
一:连接URL格式出现了问题(Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/XX","root","XXXX")
[qzhao]:我的配置如下:
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://10.111.3.244:3306/qzhao_opbook</property>
<property name="connection.username">qzhao</property>
<property name="connection.password">qzhao</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml" />
而且在我单位电脑能work
二:驱动字符串出错(com.mysql.jdbc.Driver)
三:Classpath中没有加入合适的mysql_jdbc驱动(驱动要和你的数据库版本一致)
这个我用的是mysql-connector-java-5.0.4-bin.jar,数据库是5.0
四:驱动jar包放的位置不对