我正在研究数据库我在Eclipse Luna IDE中创建了一个项目。我的数据库是在mysql中。我下载了connector / j文件并将此jar文件添加到我的项目中。这是jar文件的全名" mysql-connector-java-5.1.35-bin.jar"。但是当我运行该项目时,它将显示此错误消息"没有为jdbc找到合适的驱动程序:mysql // localhost / books"。 books是我的数据库名称。这是我的java代码。
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class DisplayAuthors {
static final String DATABASE_URL = "jdbc:mysql//localhost/books";
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection( DATABASE_URL, "saadi", "saadi" );
statement = connection.createStatement();
resultSet = statement.executeQuery( "SELECT AuthorID, FirstName, LastName FROM Authors" );
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.println( "Authors Table of Book Database:\n" );
for ( int i = 1; i < numberOfColumns; i++ )
System.out.printf( "%-8s\t", metaData.getColumnName( i ) );
System.out.println();
while ( resultSet.next() ) {
for ( int i = 1; i <= numberOfColumns; i++ )
System.out.printf( "%-8s\t", resultSet.getObject( i ) );
System.out.println();
}
}
catch ( SQLException exception ) {
exception.printStackTrace();
}
finally {
try {
resultSet.close();
statement.close();
connection.close();
}
catch ( Exception exception ) {
exception.printStackTrace();
}
}
}
}
答案 0 :(得分:0)
You have an error in the
DATABASE_URL = "jdbc:mysql//localhost/books"
: is missing .Correct one is
DATABASE_URL = "jdbc:mysql://localhost/books"
Also its kind of usual practice to first load the class before connection manager.
Class.forName("com.mysql.jdbc.Driver");