如果想要连接Mysql数据库,首先就得在该项目里面加入jdbc驱动。右击你的项目,再点击Build Path,然后点击Add External,将你的驱动加入了项目中。
Class.forName("com.mysql.jdbc.Driver");
connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","root"); 其中testjdbc为数据库名,root与root分别为用户名与密码。
直接在connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","root");后面输出一句话就行,System.out.println("数据库连接成功!");
如插入语句:String sql="insert into test(id,username,password,sex) values(0,"张三","123","男")";
PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);
ps.execute();
原文:https://www.cnblogs.com/fcy1/p/10908346.html