Unable to transfer data to mySQL database - mysql

i have a signup.jag (jaggery page) for user to register.
i have a signup.js (javascript) for javascript validation.
i want to store the user info in mysql database through java i.e. jdbc for which i have written the following code with file name sigunp.java :
import java.io.*;
import java.lang.*;
import java.sql.*;
import java.servlet.*;
import java.servlet.http.*;
public class signupdb extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException IOException
{
response.setContentType(text/html);
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost:3306/ticketing";
Connection connection;
try
{
String firstname = request.getParameter("fname");
String lastname = request.getParameter("lname");
String phonenum = request.getParameter("phone");
String addr = request.getParameter("address");
String email = request.getParameter("email");
String password = request.getParameter("pass");
pw.println(firstname);
pw.println(lastname);
pw.println(phonenum);
pw.println(addr);
pw.println(email);
pw.println(password);
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionurl,"root","suselinux");
PreparedStatement pst = connection.prepareStatement("insert into userinfo values(?,?,?,?,?,?)");
pst.setString(1,firstname);
pst.setString(2,lastname);
pst.setString(3,phonenum);
pst.setString(4,addr);
pst.setString(5,email);
pst.setString(6,password);
int i = pst.executeUpdate();
if(i != 0)
{
pw.println("<br>Record has been inserted");
}
else
{
pw.println("No Data Inserted");
}
}
catch(Exception e)
{
pw.println(e);
}
}
}
But when i started the jaggery server and submitted the data it showed me error 404.

finally i resolved it !
i created a con.jag file which has table named users :
<%
var query1 = "create table users (id int not null auto_increment, primary key(id), first_name varchar(15), last_name varchar(15), phone varchar(20), address varchar(50), email varchar(30), pass varchar(30));";
config();
var db = new Database ("jdbc:mysql://localhost:3306/tickets", "root", "password", config);
try
{
db.query(query1);
print("Table Created again");
} catch (e)
{
print(e.toString());
}
finally
{
db.close()
}
%>
then inserted the data into the database with insert_data.jag file :
<%
var frst_name = request.getParameter('fname');
var lst_name = request.getParameter('lname');
var country_name = request.getParameter('country_code');
var phon = request.getParameter('phone');
var addr = request.getParameter('address');
var mail = request.getParameter('email');
var pwd = request.getParameter('pass');
var data = "insert into users(first_name, last_name,country, phone, address, email, pass) values ('"+frst_name+"','"+lst_name+"','"+country_name+"', '"+phon+"','"+addr+"','"+mail+"','"+pwd+"')";
config();
var db = new Database ("jdbc:mysql://localhost:3306/tickets", "root", "password", config);
try
{
db.query(data);
} catch(e)
{
print(e.toString());
} finally
{
db.close()
}
%>
It really works fine !

Related

how i can retrieve from ini [odbc] for connect my app

i have some issue How i can retrieve config.ini--->[odbc] database connection into my getconnection class ? i'm using mysql database
i storage the connection into my database and Config.ini--[odbc] is fine
but when i want to retrive and connect my database into application trow config.ini i can't
check this is my database class :
public class DB(
public static String url = "jdbc:mysql://localhost/resturno?useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8";
public static String user = "root";
public static String paw = "";
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(url, user, paw);
} catch (ClassNotFoundException | SQLException ex) {
System.out.println(ex.getMessage());
System.out.println("couldn't connect!");
throw new RuntimeException(ex);
}
}
)
and this is my Config.ini :
[ODBC]
ServerName = jdbc:mysql://localhost
DataBase = resturno?useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8
Username = root
Password =
Year = 2019
and this is my readIni class :
public void readIni() {
try {
File file = new File(pathIni);
if (file.exists()) {
Wini wini = new Wini(new File(pathIni));
String url = wini.get("ODBC", "ServerName");
String dbnm = wini.get("ODBC", "DataBase");
String dbus = wini.get("ODBC", "Username");
String dbpas = wini.get("ODBC", "Password");
String dbyer = wini.get("ODBC", "Year");
if ((url != null && !url.equals("")) && (dbnm != null && !dbnm.equals("")) && (dbus != null && !dbus.equals("")) && (dbpas != null && !dbpas.equals("")) && (dbyer != null && !dbyer.equals(""))) {
Serverurl.setText(url);
dbname.setText(dbnm);
dbuser.setText(dbus);
dbpass.setText(dbpas);
dbyear.setText(dbyer);
}
}
} catch (IOException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
}
if you have anything missing i'll help me on my code
You are probably missing the port of your Database.
public static String url = "jdbc:mysql://localhost:<PORT>/resturno?useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8";
Usually the port is 3306. I hope this helps you.

MVC5 webapplication on shared hosting giving a cookie decryption error on localhost works fine

The below code is used to get the id stored in a cookie for a guest shopping cart. This code works fine on localhost but is giving me an error on shared hosting where I deployed my website.
public static class Func
{
public static string SetCookie()
{
string key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string gid = Guid.NewGuid().ToString();
var cookieText = Encoding.UTF8.GetBytes(gid);
var encryptedValue = Convert.ToBase64String(MachineKey.Protect(cookieText, key));
HttpCookie myCookie = new HttpCookie("Ecomm", encryptedValue);
myCookie.Expires = DateTime.Now.AddDays(1);
HttpContext.Current.Response.Cookies.Add(myCookie);
return gid;
}
public static UserShopCart GetCookie()
{
var usc = new UserShopCart();
string key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
HttpCookie myCookie = HttpContext.Current.Request.Cookies["Ecomm"];
if (myCookie != null)
{
if (myCookie.Value != null)
{
var output = MachineKey.Unprotect(Convert.FromBase64String(myCookie.Value), key);
usc.id = Encoding.UTF8.GetString(output);
return usc;
}
else
{
usc.id = SetCookie();
return usc;
}
}
else
{
usc.id=SetCookie();
return usc;
}
}
}
public class UserShopCart {
public string id;
public string name;
}
Here is the snapshot of the error:

how do i use select statment

I want to use select max from a table. I want to use a PreparedStatement. I have a composite primary key which consists of the t.v series and the epo number. When I add new epo it will for table and bring the t.v series code from guidline table the content of all the programs and the code for each and then add to the new table. I want it to get the last epo by getting the max and then increment +1 "an automation app".
So how can I select max where id =??
If you get me its like
pstm2=con.prepareStatement(max);
String max="select MAX(epono) as eponoo from archieve wwhere id like ? ";
This program would be helpful
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SelectRecordsUsingPreparedStatement {
public static Connection getConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:databaseName";
String username = "name";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "select deptno, deptname, deptloc from dept where deptno > ?";
pstmt = conn.prepareStatement(query); // create a statement
pstmt.setInt(1, 1001); // set input parameter
rs = pstmt.executeQuery();
// extract data from the ResultSet
while (rs.next()) {
int dbDeptNumber = rs.getInt(1);
String dbDeptName = rs.getString(2);
String dbDeptLocation = rs.getString(3);
System.out.println(dbDeptNumber + "\t" + dbDeptName + "\t" + dbDeptLocation);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Query MySQL DB using preparedStatement.setDate

public java.util.List<Tag> getAlltagsByDate(String date ){
DataSource dataSource = new DataSource();
Connection conn = dataSource.createConnection();
ResultSet resultSet = null;
PreparedStatement stmt = null;
Tag tags_Data = new Tag();
String query = "select * from tag_data where tag_data_date = ?";
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date nn =df.parse(date);
stmt = conn.prepareStatement(query);
stmt.setDate(1, java.sql.Date.valueOf(date));
resultSet = stmt.executeQuery(query);
I am getting an error
Can anyone help me with this,
I need to query mySQL db where date = input in html
No, skip the Date part; simply use the string. Let's see the value of (String date ).
MySQL is happy if you can end up with ... tag_data_date = '2015-12-11'.
If String date looks like '2015-12-11', then the conversion to Date is unnecessary.
I have presented a solution. As you have not mentioned much about your DB structure, so ,
Consider test as database name, and consisting of table tag_data having two columns id and tag_data_date as shown below.
CREATE TABLE `tag_data` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`tag_data_date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Also consider data in table as
INSERT INTO `tag_data` (`id`, `tag_data_date`) VALUES
(1, '2015-12-20 00:00:00');
And your java class as below
public class JDBCPreparedStatementExample {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver"; //mysql driver class
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/test"; //connectionstring
private static final String DB_USER = "root"; //mysql username
private static final String DB_PASSWORD = "root"; //mysql password
public static void main(String[] argv) throws ParseException {
try {
getDateForDate("2015-12-20"); //time passed as arguement
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
//Method to interact with DB and print data,this can be changed to return value of List<Key> as per your requirement
private static void getDateForDate(String date) throws SQLException, ParseException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date dateCal =df.parse(date); // parse date in String to Date Object
String updateTableSQL = "select * from tag_data where tag_data_date = ?";
try {
//get DB connection
dbConnection = getDBConnection();
// Create preapared statement
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setDate(1, new Date(dateCal.getTime()));//convert java.util.Date to java.sql.Date
// execute update SQL stetement
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getString(2);
int id = resultSet.getInt("id");
Date tag_data_date = resultSet.getDate("tag_data_date");
System.out.println("Date: " + tag_data_date);
System.out.println("Comment: " + id);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}

SEVERE: java.sql.SQLException: Column count doesn't match value count at row 1

I have Mysql datatbase, and working on servlet:
this is my Table schema:
CREATE TABLE Files (
File_Name VARCHAR(50),
File_Data Blob ,
File_Date VARCHAR(20),
File_Course_Code VARCHAR(45) REFERENCES Course(Course_Code) ,
PRIMARY KEY (File_Name , File_Date, File_Course_Code)
);
And here is the servlet code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
ServletOutputStream os = response.getOutputStream();
try {
InputStream uploadedFile = null;
DiskFileUpload fu = new DiskFileUpload();
// If file size exceeds, a FileUploadException will be thrown
fu.setSizeMax(10000000);
List fileItems = fu.parseRequest(request);
Iterator itr = fileItems.iterator();
while (itr.hasNext()) {
FileItem fi = (FileItem) itr.next();
//Check if not form field so as to only handle the file inputs
//else condition handles the submit button input
if (!fi.isFormField()) { // If the form fiel is a file
uploadedFile = fi.getInputStream();
}
}
// to get the file name:
String fileName= "String";
// to extract the date:
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String strDateNew = sdf.format(now);
HttpSession session = request.getSession();
String a = (String) session.getAttribute("fileccode");
// set connection up:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/VC", "root", "");
PreparedStatement stmt = null;
stmt = conn.prepareStatement("INSERT INTO Files (File_Name,File_Data,File_Date,File_Course_Code) VALUES (?,? ?,?)");
stmt.setString(1,fileName);
stmt.setBinaryStream(2,uploadedFile);
stmt.setString(3,strDateNew);
stmt.setString(4,a);
stmt.executeUpdate();
} catch (FileUploadException e) {
os.print(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
os.close();
}
}
I have seen many posts about this error, but almost all of them were having Syntax error in writing the query.
I have no syntax error i believe.
but maybe (File_Data) as a primary key and default null makes something wrong?
Your missing a comma
VALUES (?,? ?,?)
should be
VALUES (?,?,?,?)