我是java和netbeans的初学者。请给我完整的程序如何将我的java应用程序连接到mysql以插入数据。
答案 0 :(得分:1)
从以下链接http://sqlworkbench.mgm-tp.com/viewvc/trunk/sqlworkbench/junit/mysql-connector-java-5.1.13-bin.jar?revision=2294&pathrev=2294下载“mysql-connector-java-5.1.13-bin.jar”
以下是连接到mysql数据库并从表中检索数据的示例Java代码。
在下面的代码中,数据库名称是“databaseName”
和表名是“userTable”
别忘了将“mysql-connector-java-5.1.13-bin.jar”添加到netbeans项目的库中。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class NewClass {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://127.0.0.1:3306/";
String dbName = "databaseName";
Statement stmt = null;
ResultSet result = null;
String driver = "com.mysql.jdbc.Driver";
String databaseUserName = "root"; //user name to connect to database(plz change it with your mysql username)
String databasePassword = "root"; //password to connect to database(plz change it with your mysql password)
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, databaseUserName, databasePassword);
stmt = conn.createStatement();
result = null;
String password,username;
result = stmt.executeQuery("select * from userTable ");
if(!result.isBeforeFirst()){
System.out.println("resultset contin no rows");
}else{ // result set contain some data.... ie.. table contain some rows
// process data
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
Netbeans的知识库文章,描述how to connect to a mysql database。