In database manipulation command such as insert, update or delete can sometime throws exception due to invalid data. To protect the integrity of application data we must make sure when we a transaction was failed we must rollback
PreparedStatement ps = null;
Connection conn = null;
try {
conn = DriverManager.getConnection( URL, USERNAME, PASSWORD );
String query = "INSERT INTO tbl1(id, username) " +
"VALUES (?, ?)";
ps = conn.prepareStatement( query );
ps.setString( 1, "javaduke" );
ps.execute();
query = "INSERT INTO tbl2 (id, tbl1_id, " +
"quantity, price) VALUES (?, ?, ?, ?)";
ps = conn.prepareStatement( query );
ps.setInt( 1, id );
ps.setInt( 2, tbl_id );
ps.setInt( 3, 10 );
ps.setDouble( 4, 29.99 );
ps.execute();
}
catch ( SQLException e )
{
conn.rollback()
e.printStackTrace();
}
I guess this is Java.
Right after you get your connection object, turn off autocommit, like so.
conn = DriverManager.getConnection( URL, USERNAME, PASSWORD );
conn.setAutoCommit(false);
Right after your last execute() do this.
conn.commit();
Then the rollback() in your exception handler should do what you expect.
This should extend the scope of your transaction to beyond a single SQL query.
I set up an Apps Script program and it needs to save data to database. However, it is not working.
I have tried to use the code from Google Apps Script Documentation but I can't see how to skip the autoIncrementing field named ID and its the primary key as well.
I have used code below.
var connectionName = 'frms-db:us-central1:****';
var user = 'rj-**';
var userPwd = 'fEwnj*LAAj3****';
var db = 'CCW_CLR';
var dbUrl = 'jdbc:google:mysql://' + connectionName + '/' + db;
var conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
var stmt2 = conn.prepareStatement('INSERT INTO tblPreInterview '
+ '(ID, Timestamp, Email, Section4, Section5, Section6, Section7, Pages12_13, MinorsAtHome, FirearmsStoreage, ReferenceType1, ReferenceName1, ReferencePhone1, ReferenceType2, ReferenceName2, ReferencePhone2, ReferenceEmail2, '
+ 'ReferenceType3, ReferenceName3, ReferencePhone3, ReferenceEmail3, DeptConditions, NoGuarantee, ServicePolicy, NoRefunds, PenaltyPerjury, Authorization) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '
+ '?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
stmt2.setString(2, new Date());
stmt2.setString(3, data.email);
stmt2.setString(4, data.section4);
stmt2.setString(5, data.section5);
stmt2.setString(6, data.section6);
stmt2.setString(7, data.section8);
stmt2.setString(8, data.pages1213);
stmt2.setString(9, data.minors);
stmt2.setString(10, data.storefirearm);
stmt2.setString(11, data.reftype1);
stmt2.setString(12, data.refcon1);
stmt2.setString(13, data.refphone1);
stmt2.setString(14, data.refemail1);
stmt2.setString(15, data.reftype2);
stmt2.setString(16, data.refcon2);
stmt2.setString(17, data.refphone2);
stmt2.setString(18, data.refemail2);
stmt2.setString(19, data.reftype3);
stmt2.setString(20, data.refcon3);
stmt2.setString(21, data.refemail3);
stmt2.setString(22, data.deptcondition);
stmt2.setString(23, data.review_agree1);
stmt2.setString(24, data.review_agree2);
stmt2.setString(25, data.review_agree3);
stmt2.setString(26, data.review_agree4);
stmt2.setString(27, data.review_agree5);
stmt2.setString(28, data.signature);
stmt2.execute();
I expect to add data to my SQL database.
If the column is auto_incremented, you do not need to provide a value for it. MySQL automatically assigns a new number when you perform an insert where no value is given for that column.
So you should just not specify this column in your insert, ie change:
var stmt2 = conn.prepareStatement(
'INSERT INTO tblPreInterview '
+ '(ID, Timestamp, Email, Section4, Section5, Section6, ...
To:
'INSERT INTO tblPreInterview '
+ '(Timestamp, Email, Section4, Section5, Section6, ...
Accordingly you should remove the first parameter.
Actually i have a method where i insert some data to MySQL database via ODBC and when i get an exception i would try to update the value in the DB as most of the cases it would mean that the value yet exist.
The issue is that how can i update the DB using parameters? actually in Insert i use "?" as values and it works fine while in update it doesn't work and even by using param names it has no effects.
Here is my code
Dim sqlInsert As String = "INSERT INTO prodotti(`Cod Articolo`, `Descrizione`, `Prezzo vend`, `Prezzo Acq`, `Iva`, `Data UV`, `Reparto`, `Descrizione Reparto`, `Famiglia/Gruppo`,
`Descrizione Famiglia/Gruppo`, `Settore`, `Descrizione Settore`, `Marca`, `Cod Forn`, `Descrizione Fornitore`, `Sconto`, `RC`, `Prezzo EURO`, `Tipo_Frontal`,
N_Frontal, `Tipo Riord`, `UM`, `Unita`, `Prezzo Unita`, `Peso_Unit`, `Unita_Misura`, `Data_Crea`, `Punti Promozione`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
Dim sqlUpdate As String = "UPDATE prodotti SET Descrizione = #CodArticolo, `Prezzo vend` = #Prezzovend, `Prezzo Acq` = #PrezzoAcq, Iva = #Iva, `Data UV` = #DataUV,
Reparto = #Reparto, `Descrizione Reparto` = #DescrizioneReparto, `Famiglia/Gruppo` = #FamigliaGruppo, `Descrizione Famiglia/Gruppo` = #DescrizioneFamigliaGruppo, Settore = #Settore,
`Descrizione Settore` = #DescrizioneSettore, Marca = #Marca, `Punti Promozione` = #PuntiPromozione, `Cod Forn` = #CodForn, `Descrizione Fornitore` = #DescrizioneFornitore,
Sconto = #Sconto, Tipo_Frontal = #Tipo_Frontal, N_Frontal = #N_Frontal, `Tipo Riord` = #TipoRiord, UM = #UM, `Unita` = #Unita, `Prezzo Unita` = #PrezzoUnita, `Peso_Unit` = #PesoUnita, `Unita_Misura` = #Unita_Misura
WHERE `Cod Articolo` = #CodArticolo"
Try
dbCon.Open()
For Each Row As DataRow In data.Rows
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandType = CommandType.Text
.CommandText = sqlInsert
.Connection = dbCon
.Parameters.AddWithValue("#CodArticolo", Row.Item("Cod Articolo"))
.Parameters.AddWithValue("#Descrizione", Row.Item("Descrizione"))
.Parameters.AddWithValue("#Prezzovend", Row.Item("Prezzo vend"))
.Parameters.AddWithValue("#PrezzoAcq", Row.Item("Prezzo Acq"))
.Parameters.AddWithValue("#Iva", Row.Item("Iva"))
.Parameters.AddWithValue("#DataUV", Row.Item("Data UV"))
.Parameters.AddWithValue("#Reparto", Row.Item("Reparto"))
.Parameters.AddWithValue("#DescrizioneReparto", Row.Item("Descrizione Reparto"))
.Parameters.AddWithValue("#FamigliaGruppo", Row.Item("Famiglia/Gruppo"))
.Parameters.AddWithValue("#DescrizioneFamigliaGruppo", Row.Item("Descrizione Famiglia/Gruppo"))
.Parameters.AddWithValue("#Settore", Row.Item("Settore"))
.Parameters.AddWithValue("#DescrizioneSettore", Row.Item("Descrizione Settore"))
.Parameters.AddWithValue("#Marca", Row.Item("Marca"))
.Parameters.AddWithValue("#CodForn", Row.Item("Cod Forn"))
.Parameters.AddWithValue("#Reparto", Row.Item("Reparto"))
.Parameters.AddWithValue("#DescrizioneFornitore", Row.Item("Descrizione Fornitore"))
.Parameters.AddWithValue("#Sconto", Row.Item("Sconto"))
.Parameters.AddWithValue("#RC", Row.Item("RC"))
.Parameters.AddWithValue("#PrezzoEURO", Row.Item("Prezzo EURO"))
.Parameters.AddWithValue("#Tipo_Frontal", Row.Item("Tipo_Frontal"))
.Parameters.AddWithValue("#N_Frontal", Row.Item("N_Frontal"))
.Parameters.AddWithValue("#TipoRiord", Row.Item("Tipo Riord"))
.Parameters.AddWithValue("#UM", Row.Item("UM"))
.Parameters.AddWithValue("#Unita", Row.Item("Unita"))
.Parameters.AddWithValue("#PrezzoUnita", Row.Item("Prezzo Unita"))
.Parameters.AddWithValue("#Peso_Unit", Row.Item("Peso_Unit"))
.Parameters.AddWithValue("#Unita_Misura", Row.Item("Unita_Misura"))
.Parameters.AddWithValue("#Data_Crea", Row.Item("Data_Crea"))
.Parameters.AddWithValue("#PuntiPromozione", Row.Item("Punti Promozione"))
End With
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
Try
cmd.CommandText = sqlUpdate
cmd.ExecuteNonQuery()
Catch e As Exception
MsgBox("game over")
End Try
End Try
Next Row
Catch ex As Exception
Finally
dbCon.Close()
End Try
UPDATE
As suggested by #Mary i've declared Parameters outside the loop and initialized them inside it.
SQLBindParameter
Dim sqlInsert As String = "INSERT INTO prodotti(`Descrizione`, `Prezzo vend`, `Prezzo Acq`, `Iva`, `Data UV`, `Reparto`, `Descrizione Reparto`, `Famiglia/Gruppo`,
`Descrizione Famiglia/Gruppo`, `Settore`, `Descrizione Settore`, `Marca`, `Cod Forn`, `Descrizione Fornitore`, `Sconto`, `RC`, `Prezzo EURO`, `Tipo_Frontal`,
`N_Frontal`, `Tipo Riord`, `UM`, `Unita`, `Prezzo Unita`, `Peso_Unit`, `Unita_Misura`, `Data_Crea`, `Punti Promozione`, `Cod Articolo`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
Dim sqlUpdate As String = "UPDATE prodotti SET `Descrizione` = ?, `Prezzo vend` = ?, `Prezzo Acq` = ?, `Iva` = ?, `Data UV` = ?,
`Reparto` = ?, `Descrizione Reparto` = ?, `Famiglia/Gruppo` = ?, `Descrizione Famiglia/Gruppo` = ?, `Settore` = ?,
`Descrizione Settore` = ?, `Marca` = ?, `Cod Forn` = ?, `Descrizione Fornitore` = ?, `Sconto` = ?, `RC` = ?, `Prezzo EURO` = ?,
`Tipo_Frontal` = ?, `N_Frontal` = ?, `Tipo Riord` = ?, `UM` = ?, `Unita` = ?, `Prezzo Unita` = ?, `Peso_Unit` = ?, `Unita_Misura` = ?, `Data_Crea` = ?, `Punti Promozione` = ?
WHERE `Cod Articolo` = ?"
Dim cmd As New Odbc.OdbcCommand
With cmd
.Connection = dbCon
.CommandType = CommandType.Text
.Parameters.Add("#Descrizione", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#Prezzovend", odbcType:=Odbc.OdbcType.Double)
.Parameters.Add("#PrezzoAcq", odbcType:=Odbc.OdbcType.Double)
.Parameters.Add("#Iva", odbcType:=Odbc.OdbcType.Double)
.Parameters.Add("#DataUV", odbcType:=Odbc.OdbcType.DateTime)
.Parameters.Add("#Reparto", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#DescrizioneReparto", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#FamigliaGruppo", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#DescrizioneFamigliaGruppo", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#Settore", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#DescrizioneSettore", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#Marca", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#CodForn", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#DescrizioneFornitore", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#Sconto", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#RC", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#PrezzoEURO", odbcType:=Odbc.OdbcType.Double)
.Parameters.Add("#Tipo_Frontal", odbcType:=Odbc.OdbcType.Int)
.Parameters.Add("#N_Frontal", odbcType:=Odbc.OdbcType.Int)
.Parameters.Add("#TipoRiord", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#UM", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#Unita", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#PrezzoUnita", odbcType:=Odbc.OdbcType.Double)
.Parameters.Add("#Peso_Unit", odbcType:=Odbc.OdbcType.Double)
.Parameters.Add("#Unita_Misura", odbcType:=Odbc.OdbcType.VarChar)
.Parameters.Add("#Data_Crea", odbcType:=Odbc.OdbcType.DateTime)
.Parameters.Add("#PuntiPromozione", odbcType:=Odbc.OdbcType.Int)
.Parameters.Add("#CodArticolo", odbcType:=Odbc.OdbcType.VarChar)
End With
Try
dbCon.Open()
For Each Row As DataRow In data.Rows
cmd.CommandText = sqlInsert
cmd.Parameters("#CodArticolo").Value = Row.Item("Cod Articolo")
cmd.Parameters("#Descrizione").Value = Row.Item("Descrizione")
If IsDBNull(Row.Item("Prezzo vend")) Then
cmd.Parameters("#Prezzovend").Value = DBNull.Value
Else
cmd.Parameters("#Prezzovend").Value = Double.Parse(Row.Item("Prezzo vend"))
End If
If IsDBNull(Row.Item("Prezzo Acq")) Then
cmd.Parameters("#PrezzoAcq").Value = DBNull.Value
Else
cmd.Parameters("#PrezzoAcq").Value = Double.Parse(Row.Item("Prezzo Acq"))
End If
If IsDBNull(Row.Item("Iva")) Then
cmd.Parameters("#Iva").Value = DBNull.Value
Else
cmd.Parameters("#Iva").Value = Double.Parse(Row.Item("Iva"))
End If
If IsDBNull(Row.Item("Data UV")) Then
cmd.Parameters("#DataUV").Value = DBNull.Value
Else
cmd.Parameters("#DataUV").Value = New Date(Row.Item("Data UV"))
End If
cmd.Parameters("#Reparto").Value = Row.Item("Reparto")
cmd.Parameters("#DescrizioneReparto").Value = Row.Item("Descrizione Reparto")
cmd.Parameters("#FamigliaGruppo").Value = Row.Item("Famiglia/Gruppo")
cmd.Parameters("#DescrizioneFamigliaGruppo").Value = Row.Item("Descrizione Famiglia/Gruppo")
cmd.Parameters("#Settore").Value = Row.Item("Settore")
cmd.Parameters("#DescrizioneSettore").Value = Row.Item("Descrizione Settore")
cmd.Parameters("#Marca").Value = Row.Item("Marca")
cmd.Parameters("#CodForn").Value = Row.Item("Cod Forn")
cmd.Parameters("#DescrizioneFornitore").Value = Row.Item("Descrizione Fornitore")
cmd.Parameters("#Sconto").Value = Row.Item("Sconto")
cmd.Parameters("#RC").Value = Row.Item("RC")
If IsDBNull(Row.Item("Prezzo EURO")) Then
cmd.Parameters("#PrezzoEURO").Value = DBNull.Value
Else
cmd.Parameters("#PrezzoEURO").Value = Double.Parse(Row.Item("Prezzo EURO"))
End If
If IsDBNull(Row.Item("Tipo_Frontal")) Then
cmd.Parameters("#Tipo_Frontal").Value = DBNull.Value
Else
cmd.Parameters("#Tipo_Frontal").Value = CInt(Row.Item("Tipo_Frontal"))
End If
If IsDBNull(Row.Item("N_Frontal")) Then
cmd.Parameters("#N_Frontal").Value = DBNull.Value
Else
cmd.Parameters("#N_Frontal").Value = CInt(Row.Item("N_Frontal"))
End If
cmd.Parameters("#TipoRiord").Value = Row.Item("Tipo Riord")
cmd.Parameters("#UM").Value = Row.Item("UM")
cmd.Parameters("#Unita").Value = Row.Item("Unita")
If IsDBNull(Row.Item("Prezzo Unita")) Then
cmd.Parameters("#PrezzoUnita").Value = DBNull.Value
Else
cmd.Parameters("#PrezzoUnita").Value = Double.Parse(Row.Item("Prezzo Unita"))
End If
If IsDBNull(Row.Item("Peso_Unit")) Then
cmd.Parameters("#Peso_Unit").Value = DBNull.Value
Else
cmd.Parameters("#Peso_Unit").Value = Double.Parse(Row.Item("Peso_Unit"))
End If
cmd.Parameters("#Unita_Misura").Value = Row.Item("Unita_Misura")
If IsDBNull(Row.Item("Data_Crea")) Then
cmd.Parameters("#Data_Crea").Value = DBNull.Value
Else
cmd.Parameters("#Data_Crea").Value = New Date(Row.Item("Data_Crea"))
End If
If IsDBNull(Row.Item("Punti Promozione")) Then
cmd.Parameters("#PuntiPromozione").Value = DBNull.Value
Else
cmd.Parameters("#PuntiPromozione").Value = CInt(Row.Item("Punti Promozione"))
End If
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
Try
cmd.CommandText = sqlUpdate
cmd.ExecuteNonQuery()
Catch e As Exception
MsgBox("hai la mamma troia")
End Try
End Try
Next Row
Catch ex As Exception
Finally
dbCon.Close()
End Try
PS: i'm new in VB.NET
Use Using...End Using blocks for your database objects if the expose a .Dispose method. They need to release unmanaged objects. The Using blocks accomplish this even if there is an error.
.AddWithValue can cause some problems. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Try the .Add(String, OdbcType, Int32) method. String is the parameter name. OdbcType is the the type of the column in the database. Int32 is the size of the field, relavent to string types. Convert the types from your datatable to match. ADO.net does not always guess correctly when filling a datatable.
'Example if the field is type Int
.Parameters.Add("#CodArticolo", OdbcType.Int).Value = CInt(Row.Item("Cod Articolo"))
'Example if the field is type VarChar
.Parameters.Add("#Descrizione", OdbcType.VarChar, 50).Value = Row.Item("Descrizione")
I don't understand the reason you cannot use the MySql provider.
I am new to Java and I'm trying to insert data into a mysql database using a text file. My text file has 5 rows. I have 3 SQL insert Queries. Each query will insert 5 rows into the database.
Example queries are:
INSERT INTO `session` (`emp`, `SessionID`, `SessionDate`, `SessionStartTime`, 'SessionEndTime') VALUES (Tyler, NULL, ?, ?, ?);
INSERT INTO `session` (`emp`, `SessionID`, `SessionDate`, `SessionStartTime`,'SessionEndTime') VALUES (MAX, NULL, ?, ?, ?);
INSERT INTO `session` (`emp`, `SessionID`, `SessionDate`, `SessionStartTime`,'SessionEndTime') VALUES (James, NULL, ?, ?, ?);
Example text file:
textfile
Here is a snippet of my code. I having problems with figuring out how to read the text file and inserting it into the database. Note that the code only has one my queries. I'm trying to get one query to work before adding the others.
I'm looking for some advice on reading the file and the prepared statements for the date, start time, and end time.
any suggestions?
try
{
//Create a mysql database connection
String dbUrl = "jdbc:mysql://localhost:3306/mytest";
String username = "root"; //Database Username
String password = "abcdefg"; //Database Password
Class.forName("com.mysql.jdbc.Driver"); //Load mysql jdbc driver
Connection con = DriverManager.getConnection(dbUrl,username,password); //Create Connection to DB
// mysql query to insert data into session table
String query = " INSERT INTO `session` (`emp`, `SessionID`,
`SessionDate`, `SessionStartTime`) VALUES (Tyler, NULL, ?, ?, ?);
try {
BufferedReader bReader = new BufferedReader(newFileReader("c:/sessionstime"));
String line = "";
while ((line = bReader.readLine()) != null)
{
try
{
if (line != null)
{
String[] array = line.split(",");
for(String result:array)
{
// create mysql insert preparedstatement
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setDate (1, sessiondate[0]);
preparedStmt.setTime (2, sessionstarttime[1]);
preparedStmt.setTime (3, sessionendtime[2]);
preparedStmt.addBatch();
// execute the preparedstatement
preparedStmt.executeBatch();
// close database connection
con.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
My code is this
Profile.update_all(["is_active = ?, name = ?, geo_lat = ?, geo_long = ?, radius = ?, search_option = ?", 1, params[:profile_name],'null','null','null','st'])
but it assign
geo_lat=0
and
geo_long=0
In my database structure default value is null for both
and i want to assign null
please help me
The issue here are string 'null'.
Try the following:
Profile.update_all(["is_active = ?, name = ?, geo_lat = ?, geo_long = ?, radius = ?, search_option = ?", 1, params[:profile_name], nil, nil, nil, 'st'])
Also check your migration to see if default is not set to string 'null'.