今天给大家带来了在文本框中输入数字后,将数字传入到数据库当中,各注释已写好,不理解的请留言❀
准备好数据库的创建(不然后面的代码有可能出错)
创建database类,代码如下
public class database {
private int id;
private String name;
public int getId ( ) {
return id;
}
public void setId ( int id) {
this . id = id;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
}
代码实现
import java. awt. event. * ;
import java. sql. * ;
import javax. swing. * ;
public class cs extends JFrame implements ActionListener {
public static database d = new database ( ) ;
public static final String DRIVER = "com.mysql.jdbc.Driver" ;
public static final String URL = "jdbc:mysql://localhost:3306/cc?useSSL=false" ;
public static final String USER = "root" ;
public static final String PASSWORD = "123456" ;
private JTextField JT;
public cs ( ) {
JButton JB = new JButton ( "登录" ) ;
JB. setBounds ( 100 , 100 , 100 , 50 ) ;
this . setDefaultCloseOperation ( 3 ) ;
this . setSize ( 500 , 500 ) ;
this . setLocationRelativeTo ( null ) ;
JT = new JTextField ( 10 ) ;
JT. setBounds ( 100 , 100 , 100 , 100 ) ;
JPanel JP = new JPanel ( ) ;
JP. setBounds ( 100 , 100 , 100 , 100 ) ;
this . setLocale ( null ) ;
JP. add ( JT) ;
JP. add ( JB) ;
this . setVisible ( true ) ;
this . add ( JP) ;
JB. addActionListener ( this ) ;
}
public static void main ( String [ ] args) {
new cs ( ) ;
}
public void actionPerformed ( ActionEvent e) {
char aa[ ] = JT. getText ( ) . toCharArray ( ) ;
for ( int i = 0 ; i < aa. length; i++ ) {
if ( ! Character . isDigit ( aa[ i] ) ) {
JOptionPane . showMessageDialog ( null , "请输入的必须为数字!!" ) ;
return ;
}
}
d. setName ( JT. getText ( ) ) ;
Connection con = null ;
PreparedStatement pstmt = null ;
try {
Class . forName ( DRIVER) ;
con = DriverManager . getConnection ( URL, USER, PASSWORD) ;
System . out. println ( "连接成功" ) ;
String sql = "INSERT kk VALUES(DEFAULT,?)" ;
pstmt = con. prepareStatement ( sql) ;
System . out. println ( "成功插入:" + d. getName ( ) ) ;
pstmt. setString ( 1 , d. getName ( ) ) ;
int result = pstmt. executeUpdate ( ) ;
} catch ( Exception ee) {
ee. printStackTrace ( ) ;
}
}
}
最终的类如下