create table student
(
id int,
name nvarchar(7),
age nvarchar(5)
)
怎用JAVA写语句向表里插入数据呢?
[code="java"]String user = "root"; //用户名
String pass = "root"; //密码
[/code]
看看你的用户名、密码对不对。
[code="java"]
public class insertStudent{
public static void main(String args[]) {
Connection con = null;
PreparedStatement pst = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "komal";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(false);// Disables auto-commit.
String sql = "insert into student values(?,?) ";
pst = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
pst.setString(1, "Rakesh");
pst.setString(2, "18");
pst.executeUpdate();
pst.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
[/code]
这个是MySql的实现,主键在数据库中要设为自动增长的 autoincrement
报什么错?把异常给我,你在数据库中把id字段设为自动增长的!
[code="Sql"]
drop table student ;
create table student
(
id int primary key not null auto_increment, //自动增加
name nvarchar(7),
age nvarchar(5)
)
[/code]